java导出excel表格
作者:互联网
本篇所有资源来自于apache官方资源
http://poi.apache.org/components/spreadsheet/quick-guide.html
话不多说,实操,本篇只介绍基础,不涉及业务
1.导入依赖,版本自己选择合适的,不同版本可能方法不同,注意看官方网站
<!--excel表格 --> <dependency> <groupId>org.apache.poi</groupId> <artifactId>poi</artifactId> <version>3.17</version> </dependency> <dependency> <groupId>org.apache.poi</groupId> <artifactId>poi-ooxml</artifactId> <version>3.17</version> </dependency>
2.首先写控制层
@RestController public class ExcelController { @Autowired private ExcelService excelService; @RequestMapping("exportExcelMode") public void exportExcelMode(HttpServletResponse response) { OutputStream outputStream = null; try { outputStream = response.getOutputStream(); response.setContentType("application/octet-stream"); response.addHeader("Content-Disposition", "attachment;filename=" + URLEncoder.encode("用户表" + ".xlsx", "utf-8")); excelService.exportExcelMode(outputStream); } catch (Exception e) { e.printStackTrace(); } } }
2.写导出方法exportExcelMode
@Service public class ExcelService { public void exportExcelMode(OutputStream outputStream){ try { //用来做第一行的标题行 String[] field =new String[]{"序号","用户名","密码"}; //建立工作区 XSSFWorkbook workbook = new XSSFWorkbook(); //创建工作表 XSSFSheet sheet = workbook.createSheet("用户册"); //创建第一行 XSSFRow row = sheet.createRow(0); //创建样式 XSSFCellStyle cellStyle = workbook.createCellStyle(); Font font = workbook.createFont(); font.setFontName("宋体"); //设置字体大小 font.setFontHeightInPoints((short) 11); //设置字体样式 cellStyle.setFont(font); cellStyle.setBorderBottom(BorderStyle.THIN); //下边框 cellStyle.setBorderLeft(BorderStyle.THIN);//左边框 cellStyle.setBorderTop(BorderStyle.THIN);//上边框 cellStyle.setBorderRight(BorderStyle.THIN);//右边框 //垂直居中 cellStyle.setVerticalAlignment(VerticalAlignment.CENTER); //更多样式去官网上看 for (int i=0;i<field.length;i++){ //获取列 XSSFCell cell = row.createCell(i); //给该列设置值 cell.setCellValue(field[i]); //设置该列的样式 cell.setCellStyle(cellStyle); //设置列宽 sheet.setColumnWidth(i,256*30); } //创建第二行 row = sheet.createRow(1); //第二行第一列 XSSFCell cell = row.createCell(0); cell.setCellStyle(cellStyle); cell.setCellValue(1); //第二行第二列 cell = row.createCell(1); cell.setCellStyle(cellStyle); cell.setCellValue("zhangSan"); //第二行第三列 cell = row.createCell(2); cell.setCellStyle(cellStyle); cell.setCellValue("123456"); workbook.setSheetName(0,"用户表"); workbook.write(outputStream); }catch (Exception e){ e.printStackTrace(); }finally { if(outputStream!=null){ try { outputStream.close(); } catch (IOException e) { e.printStackTrace(); } } } } }
3.测试
4.总结
更多的操作,例如合并单元格什么的可以参考官方文档,http://poi.apache.org/components/spreadsheet/quick-guide.html
这部分一般采用循环生成,有数组对象,直接遍历
标签:cellStyle,outputStream,java,表格,excel,exportExcelMode,THIN,poi,apache 来源: https://blog.csdn.net/weixin_49100429/article/details/119214881