> 文档中心 > java中使用poi生成excel文件,复制可用

java中使用poi生成excel文件,复制可用

maven依赖

       org.apache.poi     poi-ooxml 

将list集合生成excel文件

  List payList = baseTransferOrderMapper.selectBySuccess(); SimpleDateFormat dateInit = new SimpleDateFormat("yyyy-MM-dd HH:mm:ss");  Date date = new Date(); SimpleDateFormat format = new SimpleDateFormat("yyyyMMdd"); String nowDay = format.format(date); Workbook wb = new XSSFWorkbook(); //标题行抽出字段 String[] title = {"表头1","表头2", "表头3", "表头4", "表头5", "表头6", "表头7", "表头8","表头9"}; //设置sheet名称,并创建新的sheet对象 String sheetName = nowDay+"交易订单"; Sheet stuSheet = wb.createSheet(sheetName); //获取表头行 Row titleRow = stuSheet.createRow(0); //创建单元格,设置style居中,字体,单元格大小等 CellStyle style = wb.createCellStyle(); Cell cell = null; //把已经写好的标题行写入excel文件中 for (int i = 0; i < title.length; i++) {     cell = titleRow.createCell(i);     cell.setCellValue(title[i]);     cell.setCellStyle(style); } //把从数据库中取得的数据一一写入excel文件中 Row row = null; for (int i = 0; i < payList .size(); i++) {     //创建list.size()行数据     row = stuSheet.createRow(i + 1);     //把值一一写进单元格里     //设置第一列为自动递增的序号     row.createCell(0).setCellValue(payList.get(i).getVaule1());     row.createCell(1).setCellValue(payList.get(i).getVaule2());     row.createCell(2).setCellValue(payList.get(i).getVaule3());     row.createCell(3).setCellValue(payList.get(i).getVaule4());     row.createCell(4).setCellValue(payList.get(i).getVaule5());     row.createCell(5).setCellValue(payList.get(i).getVaule6());     row.createCell(6).setCellValue(payList.get(i).getVaule7());     row.createCell(7).setCellValue(payList.get(i).getVaule8());     row.createCell(8).setCellValue(payList.get(i).getVaule9()); } //设置单元格宽度自适应,在此基础上把宽度调至1.5倍 for (int i = 0; i < title.length; i++) {     stuSheet.autoSizeColumn(i, true);     stuSheet.setColumnWidth(i, stuSheet.getColumnWidth(i) * 15 / 10); } //获取配置文件中保存对应excel文件的路径,本地也可以直接写成本地路径路径 String folderPath ="D:/ce/upload" + File.separator + "ftp"; //创建上传文件目录 File folder = new File(folderPath); //如果文件夹不存在创建对应的文件夹 if (!folder.exists()) {     folder.mkdirs(); } //设置文件名 String fileName = sheetName + ".xlsx"; String savePath = folderPath + File.separator + fileName; // System.out.println(savePath); OutputStream fileOut = null; try {     fileOut = new FileOutputStream(savePath);     wb.write(fileOut);     fileOut.close(); } catch (Exception e) {     e.printStackTrace(); }

保存结果

 

服务器123