将数据导出Excel文件工具类

来源:互联网 发布:王者荣耀 项羽 知乎 编辑:程序博客网 时间:2024/06/05 17:51

直接上代码,直接复制即可


package com.tx.cs.util;


import java.io.File;
import java.io.FileInputStream;
import java.io.FileOutputStream;
import java.io.IOException;
import java.io.OutputStream;
import java.util.List;
import java.util.Map;

import org.apache.poi.hssf.usermodel.HSSFCell;
import org.apache.poi.hssf.usermodel.HSSFCellStyle;
import org.apache.poi.hssf.usermodel.HSSFRichTextString;
import org.apache.poi.hssf.usermodel.HSSFRow;
import org.apache.poi.hssf.usermodel.HSSFSheet;
import org.apache.poi.hssf.usermodel.HSSFWorkbook;
import org.apache.poi.ss.usermodel.Cell;
import org.apache.poi.ss.usermodel.Row;
import org.apache.poi.ss.usermodel.Sheet;
import org.apache.poi.ss.usermodel.Workbook;
import org.apache.poi.xssf.usermodel.XSSFWorkbook;


/**
 * excel導出工具類
 * @author hzw
 * @version 创建时间:2016/12/16 下午1:49:49 
 */
public class WriteExcelUtil {
private static final String EXCEL_XLS = "xls";  
   private static final String EXCEL_XLSX = "xlsx";  
 
   /**
    * 道入數據
    * @param dataList 數據集
    * @param cloumnCount 總列數
    * @param rowNumber 从第几行开始插入数据
    * @param finalXlsxPath
    */
   public static void writeExcel(List<Map> dataList,int rowNumber, int cloumnCount,String finalXlsxPath){  
       OutputStream out = null;  
       try {  
           // 获取总列数  
           int columnNumCount = cloumnCount;  
           // 读取Excel文档  
           File finalXlsxFile = new File(finalXlsxPath);  
           Workbook workBook = getWorkbok(finalXlsxFile);  
           // sheet 对应一个工作页  
           Sheet sheet = workBook.getSheetAt(0);  
           /** 
            * 删除原有数据,除了属性列 
            */  
           //int rowNumber = sheet.getLastRowNum();  // 第一行从0开始算  
           System.out.println("原始数据总行数,除属性列:" + rowNumber);  
           for (int i = 1; i <= rowNumber; i++) {  
               Row row = sheet.getRow(i);  
               sheet.removeRow(row);  
           }  
           // 创建文件输出流,输出电子表格:这个必须有,否则你在sheet上做的任何操作都不会有效  
           out =  new FileOutputStream(finalXlsxPath);  
           workBook.write(out);  
           /** 
            * 往Excel中写新数据 
            */  
           for (int j = 0; j < dataList.size(); j++) {  
               // 创建一行:从第二行开始,跳过属性列  
               Row row = sheet.createRow(j + 1);  
               // 得到要插入的每一条记录  
               Map dataMap = dataList.get(j);  
               for (int k = 0; k <= columnNumCount; k++) {  
               // 在一行内循环  
               String param = dataMap.get("param"+k).toString();  
               Cell cell = row.createCell(k);  
               cell.setCellValue(param);  
               }  
           }  
           // 创建文件输出流,准备输出电子表格:这个必须有,否则你在sheet上做的任何操作都不会有效  
           out =  new FileOutputStream(finalXlsxPath);  
           workBook.write(out);  
       } catch (Exception e) {  
           e.printStackTrace();  
       } finally{  
           try {  
               if(out != null){  
                   out.flush();  
                   out.close();  
               }  
           } catch (IOException e) {  
               e.printStackTrace();  
           }  
       }  
       System.out.println("數據導出成功");  
   }  
   
   /**
    * 道出數據
    * @param dataList 數據集
    * @param cloumnCount 總列數
    * @param rowNumber 从第几行开始插入数据(從0開始)
    * @param templatePath 模板Excel路徑
    * @param finalXlsxPath 生成地址
    */
   public static void writeExcelByTemplate(List<Map> dataList,int rowNumber, int cloumnCount, String templatePath, String finalXlsxPath){  
       OutputStream out = null;  
       try {  
           // 获取总列数  
           int columnNumCount = cloumnCount;  
           // 读取Excel文档  
           File finalXlsxFile = new File(templatePath);
           Workbook workBook = getWorkbok(finalXlsxFile);  
           // sheet 对应一个工作页  
           Sheet sheet = workBook.getSheetAt(0);  
           // 创建文件输出流,输出电子表格:这个必须有,否则你在sheet上做的任何操作都不会有效  
           out =  new FileOutputStream(finalXlsxPath);  
           workBook.write(out);  
           /** 
            * 往Excel中写新数据 
            */ 
           if(dataList!=null&&dataList.size()>0){
           for (int j = 0; j < dataList.size(); j++) {  
               // 创建一行:从第二行开始,跳过属性列  
               Row row = sheet.createRow(j + rowNumber);  
               // 得到要插入的每一条记录  
               Map dataMap = dataList.get(j);  
               for (int k = 0; k <= columnNumCount; k++) {  
               // 在一行内循环  
               String param = dataMap.get("param"+(k+1))!=null?dataMap.get("param"+(k+1)).toString():"";;  
               Cell cell = row.createCell(k);  
               cell.setCellValue(param);  
               }  
           }  
           }
           // 创建文件输出流,准备输出电子表格:这个必须有,否则你在sheet上做的任何操作都不会有效  
           out =  new FileOutputStream(finalXlsxPath);  
           workBook.write(out);  
       } catch (Exception e) {  
           e.printStackTrace();  
       } finally{  
           try {  
               if(out != null){  
                   out.flush();  
                   out.close();  
               }  
           } catch (IOException e) {  
               e.printStackTrace();  
           }  
       }  
       System.out.println("數據導出成功");  
   }
 
   /** 
    * 判断Excel的版本,获取Workbook 
    * @param in 
    * @param filename 
    * @return 
    * @throws IOException 
    */  
   public static Workbook getWorkbok(File file) throws IOException{  
       Workbook wb = null;  
       FileInputStream in = new FileInputStream(file);  
       if(file.getName().endsWith(EXCEL_XLS)){  //Excel 2003  
           wb = new HSSFWorkbook(in);  
       }else if(file.getName().endsWith(EXCEL_XLSX)){  // Excel 2007/2010  
           wb = new XSSFWorkbook(in);  
       }  
       return wb;  
   }  
   
   //导出excel
   public static void exportExcel(String title, String[] headers,List<Map> dataList, String parameter, String fileRoot, String crecheId,String fileName) {
       // 聲明一個工作簿
       HSSFWorkbook workbook = new HSSFWorkbook();
       // 生成一個表格
       // HSSFSheet sheet = workbook.createSheet(title);
       HSSFSheet sheet = workbook.createSheet();
       // 設置表格默認列寬
       // sheet.setDefaultColumnWidth((short)20);
       // 生成樣式
       HSSFCellStyle style = workbook.createCellStyle();


       // 設置單元格自動換行
       // style2.setWrapText(true);


       // //添加表頭
       // HSSFHeader header = sheet.getHeader();
       // header.setCenter(title);


       // 生成表格標題行
       HSSFRow row = sheet.createRow(0);
       row.setHeight((short) 600);
       for (short i = 0; i < headers.length; i++) {
           HSSFCell cell = row.createCell(i);
           cell.setCellStyle(style);
           HSSFRichTextString text = new HSSFRichTextString(headers[i]);
           cell.setCellValue(text);
       }
       int columnNumCount = headers.length;
       for (int j = 0; j < dataList.size(); j++) {  
                // 创建一行:从第二行开始,跳过属性列  
        row = sheet.createRow(j + 1); 
                // 得到要插入的每一条记录  
                Map dataMap = dataList.get(j);  
                for (int k = 0; k < columnNumCount; k++) {  
               // 在一行内循环  
                String param = dataMap.get("param"+(k+1))!=null?dataMap.get("param"+(k+1)).toString():"";  
               Cell cell = row.createCell(k);  
               cell.setCellValue(param);  
                }  
            } 
      // 生成excel文件
       try {
        String fileMkdirsPending=fileRoot+"/"+crecheId;
           File mkdirsPending= new File(fileMkdirsPending);
           if(!mkdirsPending.exists()){
               mkdirsPending.mkdirs();
           }
           String filePath =  fileMkdirsPending +"/" + fileName+".xls";
           FileOutputStream fos = new FileOutputStream(filePath);
           workbook.write(fos);
           fos.close();
       } catch (Exception e) {
           e.printStackTrace();
       }
 }
}
原创粉丝点击