package com.zhcs.dt.service.information.annualPlan; import java.io.BufferedInputStream; import java.io.BufferedOutputStream; import java.io.File; import java.io.FileInputStream; import java.io.FileOutputStream; import java.io.InputStream; import java.io.OutputStream; import java.net.URLEncoder; import java.util.List; import javax.servlet.http.HttpServletResponse; import org.apache.poi.ss.usermodel.BorderStyle; import org.apache.poi.ss.usermodel.HorizontalAlignment; import org.apache.poi.ss.usermodel.IndexedColors; import org.apache.poi.ss.usermodel.VerticalAlignment; import org.apache.poi.ss.util.CellRangeAddress; import org.apache.poi.xssf.usermodel.XSSFCell; import org.apache.poi.xssf.usermodel.XSSFCellStyle; import org.apache.poi.xssf.usermodel.XSSFRow; import org.apache.poi.xssf.usermodel.XSSFSheet; import org.apache.poi.xssf.usermodel.XSSFWorkbook; import org.springframework.stereotype.Component; import com.zhcs.dt.util.PageData; @Component public class ExcelUtils { /** *tempPath 模板文件路径 *path 文件路径 *list 集合数据 */ public void exportExcel(String fileName, String path, HttpServletResponse response, List list,String keyStr) { String tempPath = path + "\\" + fileName; File newFile = createNewFile(tempPath, path); InputStream is = null; XSSFWorkbook workbook = null; XSSFSheet sheet = null; try { is = new FileInputStream(newFile);// 将excel文件转为输入流 workbook = new XSSFWorkbook(is);// 创建个workbook, // 获取第一个sheet sheet = workbook.getSheetAt(0); } catch (Exception e1) { e1.printStackTrace(); } if (sheet != null) { try { // 写数据 FileOutputStream fos = new FileOutputStream(newFile); XSSFRow row = sheet.getRow(0); if (row == null) { row = sheet.createRow(0); } XSSFCell cell = row.getCell(0); if (cell == null) { cell = row.createCell(0); } cell.setCellValue(""); // 合并单元格 CellRangeAddress region = new CellRangeAddress(3,2+list.size(),1,1); sheet.addMergedRegion(region); String[] keyArry = keyStr.split(","); for (int i = 0; i < list.size(); i++) { PageData map = list.get(i); row = sheet.createRow(i+3); //从第四行开始 cell = setCell(workbook,row,0); createRowAndCell(i+1, row, cell, 0); cell = setCell(workbook,row,1); if (i == 0) createRowAndCell(map.get("COMPANY"), row, cell, 1); else createRowAndCell("", row, cell, 1); for (int j = 0; j < keyArry.length; j++) { cell = setCell(workbook,row,j+2); createRowAndCell(map.get(keyArry[j]), row, cell, j+2); } } workbook.write(fos); fos.flush(); fos.close(); // 下载 InputStream fis = new BufferedInputStream(new FileInputStream(newFile)); byte[] buffer = new byte[fis.available()]; fis.read(buffer); fis.close(); response.reset(); response.setContentType("text/html;charset=UTF-8"); OutputStream toClient = new BufferedOutputStream( response.getOutputStream()); response.setContentType("application/x-msdownload"); String newName = URLEncoder.encode(fileName,"UTF-8"); response.addHeader("Content-Disposition", "attachment;filename=\"" + newName + "\""); response.addHeader("Content-Length", "" + newFile.length()); toClient.write(buffer); toClient.flush(); } catch (Exception e) { e.printStackTrace(); } finally { try { if (null != is) { is.close(); } } catch (Exception e) { e.printStackTrace(); } } } // 删除创建的新文件 this.deleteFile(newFile); } /** *根据当前row行,来创建index标记的列数,并赋值数据 */ private void createRowAndCell(Object obj, XSSFRow row, XSSFCell cell, int index) { cell = row.getCell(index); if (cell == null) { cell = row.createCell(index); } if (obj != null) cell.setCellValue(obj.toString()); else cell.setCellValue(""); } /** * 复制文件 * @param s * 源文件 * @param t * 复制到的新文件 */ public void fileChannelCopy(File s, File t) { try { InputStream in = null; OutputStream out = null; try { in = new BufferedInputStream(new FileInputStream(s), 1024); out = new BufferedOutputStream(new FileOutputStream(t), 1024); byte[] buffer = new byte[1024]; int len; while ((len = in.read(buffer)) != -1) { out.write(buffer, 0, len); } } finally { if (null != in) { in.close(); } if (null != out) { out.close(); } } } catch (Exception e) { e.printStackTrace(); } } /** * 读取excel模板,并复制到新文件中供写入和下载 * * @return */ public File createNewFile(String tempPath, String rPath) { // 读取模板,并赋值到新文件 // 文件模板路径 String path = (tempPath); File file = new File(path); // 保存文件的路径 String realPath = rPath; // 新的文件名 String newFileName = System.currentTimeMillis() + ".xlsx"; // 判断路径是否存在 File dir = new File(realPath); if (!dir.exists()) { dir.mkdirs(); } // 写入到新的excel File newFile = new File(realPath, newFileName); try { newFile.createNewFile(); // 复制模板到新文件 fileChannelCopy(file, newFile); } catch (Exception e) { e.printStackTrace(); } return newFile; } /** * 下载成功后删除 * * @param files */ private void deleteFile(File... files) { for (File file : files) { if (file.exists()) { file.delete(); } } } private XSSFCellStyle setStyle(XSSFWorkbook workbook) { XSSFCellStyle style = workbook.createCellStyle(); style.setAlignment(HorizontalAlignment.CENTER); style.setBorderBottom(BorderStyle.THIN); style.setRightBorderColor(IndexedColors.BLACK.getIndex()); style.setBorderLeft(BorderStyle.THIN); style.setLeftBorderColor(IndexedColors.BLACK.getIndex()); style.setBorderTop(BorderStyle.THIN); style.setTopBorderColor(IndexedColors.BLACK.getIndex()); style.setBorderBottom(BorderStyle.THIN); style.setBottomBorderColor(IndexedColors.BLACK.getIndex()); style.setVerticalAlignment(VerticalAlignment.CENTER); return style; } private XSSFCell setCell(XSSFWorkbook workbook,XSSFRow row,int num){ XSSFCell cell = row.createCell(num); XSSFCellStyle style = setStyle(workbook); cell.setCellStyle(style); return cell; } }