使用poi导出excel并打包的一种方法

来源:互联网 发布:爱知 流星 编辑:程序博客网 时间:2024/05/21 09:17

1、前提:在HttpServlet中的service()等方法中使用。

2、

  1. package com.isoftstone.runbat.util;
  2. import java.io.File;
  3. import java.io.FileInputStream;
  4. import java.io.FileOutputStream;
  5. import java.io.IOException;
  6. import java.io.InputStream;
  7. import java.io.OutputStream;
  8. import java.math.BigDecimal;
  9. import java.sql.Date;
  10. import java.sql.ResultSetMetaData;
  11. import java.util.zip.ZipEntry;
  12. import java.util.zip.ZipOutputStream;
  13. import javax.sql.RowSet;
  14. import org.apache.poi.hssf.usermodel.HSSFCell;
  15. import org.apache.poi.hssf.usermodel.HSSFCellStyle;
  16. import org.apache.poi.hssf.usermodel.HSSFFont;
  17. import org.apache.poi.hssf.usermodel.HSSFRow;
  18. import org.apache.poi.hssf.usermodel.HSSFSheet;
  19. import org.apache.poi.hssf.usermodel.HSSFWorkbook;
  20. import org.slf4j.Logger;
  21. import org.slf4j.LoggerFactory;
  22. import oracle.sql.TIMESTAMP;
  23. import com.isoftstone.fwk.util.SpringUtils;
  24. public class ExportExcelUtil {
  25.     private static Logger logger = LoggerFactory.getLogger(ExportExcelUtil.class);
  26.     
  27.     /**
  28.      * @param sql
  29.      *            查询数据的sql
  30.      * @param outputStream
  31.      *            输出流
  32.      * @param sheetName
  33.      *            工作薄中工作表的名字
  34.      */
  35.     public void exportExcel(String sql, OutputStream outputStream,String sheetName) {
  36.         HSSFWorkbook wb = new HSSFWorkbook();// 声明一个工作薄
  37.         HSSFCellStyle style = wb.createCellStyle(); // 一个样式
  38.         style.setVerticalAlignment(HSSFCellStyle.VERTICAL_CENTER); // 设置垂直居中
  39.         style.setAlignment(HSSFCellStyle.ALIGN_CENTER); // 水平居中
  40.         HSSFFont headerFont = (HSSFFont) wb.createFont(); // 创建字体样式
  41.         headerFont.setBoldweight(HSSFFont.BOLDWEIGHT_BOLD);// 字体加粗
  42.         headerFont.setFontName("Times New Roman"); // 设置字体类型
  43.         headerFont.setFontHeightInPoints((short) 8); // 设置字体大小
  44.         style.setFont(headerFont); // 为标题样式设置字体样式
  45.         /*
  46.          * style.setBorderBottom(HSSFCellStyle.BORDER_THIN); // 下边框
  47.          * style.setBorderLeft(HSSFCellStyle.BORDER_THIN);// 左边框
  48.          * style.setBorderTop(HSSFCellStyle.BORDER_THIN);// 上边框
  49.          * style.setBorderRight(HSSFCellStyle.BORDER_THIN);// 右边框
  50.          */
  51.         style.setWrapText(true);
  52.         HSSFSheet sheet = wb.createSheet(sheetName);// 声明工作薄里中一个工作表的名字
  53.         sheet.setDefaultColumnWidth(30);// 给工作一个默认长度
  54.         HSSFRow row = sheet.createRow(0); // 创建第一行(也可以称为表头)
  55.         try {
  56.             // 通过传过来的sql获得数据
  57.             RowSet rowSet = SpringUtils.getCommonDao().queryNativeSQL(sql,null, false);
  58.             ResultSetMetaData columnNames = rowSet.getMetaData();
  59.             int columnValues = columnNames.getColumnCount();
  60.             for (int i = 0; i < columnValues; i++) {
  61.                 HSSFCell cell = row.createCell(i);
  62.                 cell.setCellStyle(style);
  63.                 cell.setCellValue(columnNames.getColumnName(i + 1));
  64.             }
  65.             int rowNo = 1;
  66.             int m = 1;
  67.             /*
  68.              * HSSFFont contextFont = (HSSFFont) wb.createFont(); //创建字体样式
  69.              * contextFont.setBoldweight(HSSFFont.BOLDWEIGHT_NORMAL);//字体加粗
  70.              * style.setFont(contextFont);
  71.              */
  72.             while (rowSet.next()) {
  73.                 row = sheet.createRow(rowNo);
  74.                 for (int columnNo = 0; columnNo < columnValues; columnNo++) {
  75.                     HSSFCell cell = row.createCell(columnNo);
  76.                     // cell.setCellStyle(style);
  77.                     Object columnValue = rowSet.getObject(columnNo + 1);
  78.                     if (columnValue == null) {
  79.                         continue;
  80.                     }
  81.                     if (columnValue instanceof String) {
  82.                         cell.setCellValue(rowSet.getString(columnNo + 1));
  83.                     } else if (columnValue instanceof Integer) {
  84.                         cell.setCellValue(rowSet.getInt(columnNo + 1));
  85.                     } else if (columnValue instanceof Double) {
  86.                         cell.setCellValue(rowSet.getDouble(columnNo + 1));
  87.                     } else if (columnValue instanceof Date) {
  88.                         cell.setCellValue(rowSet.getDate(columnNo + 1));
  89.                     } else if (columnValue instanceof TIMESTAMP) {
  90.                         cell.setCellValue(rowSet.getTimestamp(columnNo + 1));
  91.                     } else if (columnValue instanceof BigDecimal) {
  92.                         cell.setCellValue(rowSet.getBigDecimal(columnNo + 1).doubleValue());
  93.                     }
  94.                 }
  95.                 if (rowNo % 60000 == 0) {
  96.                     m++;
  97.                     sheet = wb.createSheet(sheetName + m);// 声明工作薄里中一个工作表的名字
  98.                     sheet.setDefaultColumnWidth(30);// 给工作一个默认长度
  99.                     row = sheet.createRow(0); // 创建第一行(也可以称为表头)
  100.                     for (int i = 0; i < columnValues; i++) {
  101.                         HSSFCell cell = row.createCell(i);
  102.                         cell.setCellStyle(style);
  103.                         cell.setCellValue(columnNames.getColumnName(i + 1));
  104.                     }
  105.                     rowNo = 0;
  106.                 }
  107.                 rowNo++;
  108.             }
  109.             String name = "batch_excel";
  110.             File fileBatch = new File(this.getPath()+"batch_excel");
  111.             if(!fileBatch.exists()){
  112.                 fileBatch.mkdir();
  113.             }
  114.             //默认导出到D盘下
  115.             FileOutputStream out = new FileOutputStream(fileBatch+"/"+name+".xls");
  116.             wb.write(out);
  117.             out.flush();
  118.             out.close();// 关闭流
  119.             logger.info("导出"+sheetName+"成功");
  120.             this.putExcelToZip(sheetName,name,outputStream);
  121.         } catch (Exception e) {
  122.             e.printStackTrace();
  123.             logger.error("导出"+sheetName+"失败");
  124.         }
  125.     }
  126.     
  127.     public void putExcelToZip(String sheetName,String name,OutputStream outputStream) throws IOException{
  128.         File file = new File(this.getPath()+"batch_excel/"+name+".xls");
  129.         //File zipFile = new File(this.getPath()+"batch_excel/"+sheetName+".zip");
  130.         InputStream input = new FileInputStream(file);
  131.         ZipOutputStream zipOut = new ZipOutputStream(outputStream);
  132.         ZipEntry zipEntry = new ZipEntry(file.getName());
  133.         zipOut.putNextEntry(zipEntry);
  134.         // 设置注释
  135.         zipOut.setComment("hello");
  136.         int temp = 0;
  137.         while ((temp = input.read()) != -1) {
  138.             zipOut.write(temp);
  139.         }
  140.        if(file.isFile()){
  141.             file.delete();
  142.             logger.info("删除excel文件");
  143.         }

  144.         input.close();
  145.         zipOut.close();
  146.         logger.info("保存zip文件");
  147.      
  148.     }
  149.     
  150.     public String getPath(){
  151.         String path = ExportExcelUtil.class.getResource("/").getPath();
  152.         path = path.substring(0, path.indexOf("WEB-INF"));
  153.         return path;
  154.     }
  155. }


0 0
原创粉丝点击