1. 程式人生 > >Java POI 匯出EXCEL

Java POI 匯出EXCEL

1、寫成了通過工具包,拿來即可用

ps:如果要加屬性只需要在裡面加一點程式碼即可

import java.io.BufferedInputStream;
import java.io.BufferedOutputStream;
import java.io.ByteArrayInputStream;
import java.io.ByteArrayOutputStream;
import java.io.IOException;
import java.io.InputStream;
import java.lang.reflect.Method;
import java.util.List;
import
javax.servlet.ServletOutputStream; import javax.servlet.http.HttpServletResponse; import org.apache.poi.hssf.usermodel.HSSFCell; import org.apache.poi.hssf.usermodel.HSSFCellStyle; 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; public class ExcelUtil { /** * * @param res * @param title 對應的列標題 * @param exportData 需要匯出的資料 * @param fileds 列標題對應的實體類的屬性 * @throws IOException */ public static void exportExcel(HttpServletResponse res, List<String> title, List exportData, String fileds[]) throws
IOException { // 1.建立一個workbook,對應一個Excel檔案 HSSFWorkbook wb = new HSSFWorkbook(); // 2.在workbook中新增一個sheet,對應Excel中的一個sheet HSSFSheet sheet = wb.createSheet("new sheet"); // 3.在sheet中新增表頭第0行,老版本poi對excel行數列數有限制short HSSFRow row = sheet.createRow((int) 0); // 4.建立單元格,設定值表頭,設定表頭居中 HSSFCellStyle style = wb.createCellStyle(); // 居中格式 style.setAlignment(HSSFCellStyle.ALIGN_CENTER); // 設定表頭 for (int i = 0; i < title.size(); i++) { HSSFCell cell = row.createCell(i); cell.setCellValue(title.get(i)); cell.setCellStyle(style); } int size = 2; // 迴圈將資料寫入Excel for (int j = 0; exportData != null && !exportData.isEmpty() && j < exportData.size(); j++) { Class clazz = exportData.get(j).getClass(); String[] contents = new String[fileds.length]; for (int i = 0; fileds != null && i < fileds.length; i++) { String filedName = toUpperCaseFirstOne(fileds[i]); Object obj = null; try { Method method = clazz.getMethod(filedName); method.setAccessible(true); obj = method.invoke(exportData.get(j)); } catch (Exception e) { } String str = String.valueOf(obj); if (str == null || str.equals("null")) str = ""; contents[i] = str; } size++; row = sheet.createRow(size); for (int n = 0; n < contents.length; n++) { // 將生成的單元格新增到工作表中 row.createCell(n).setCellValue(contents[n]); } } //獲取當前列的寬度,然後對比本列的長度,取最大值 for (int columnNum = 0; columnNum <= fileds.length; columnNum++) { int columnWidth = sheet.getColumnWidth(columnNum) / 256; for (int rowNum = 0; rowNum <= sheet.getLastRowNum(); rowNum++) { Row currentRow; //當前行未被使用過 if (sheet.getRow(rowNum) == null) { currentRow = sheet.createRow(rowNum); } else { currentRow = sheet.getRow(rowNum); } if(currentRow.getCell(columnNum) != null) { Cell currentCell = currentRow.getCell(columnNum); int length = currentCell.toString().getBytes("GBK").length; if (columnWidth < length + 1) { columnWidth = length + 1; } } } sheet.setColumnWidth(columnNum, columnWidth * 256); //設定寬度 } // 使用瀏覽器下載 String fileName = "資料匯出表"; ByteArrayOutputStream os = new ByteArrayOutputStream(); wb.write(os); byte[] content = os.toByteArray(); InputStream is = new ByteArrayInputStream(content); // 設定response引數,可以開啟下載頁面 res.reset(); res.setContentType("application/vnd.ms-excel;charset=utf-8"); res.setHeader("Content-Disposition", "attachment;filename=" + new String((fileName + ".xls").getBytes(), "iso-8859-1")); ServletOutputStream out = res.getOutputStream(); BufferedInputStream bis = null; BufferedOutputStream bos = null; try { bis = new BufferedInputStream(is); bos = new BufferedOutputStream(out); byte[] buff = new byte[2048]; int bytesRead; while (-1 != (bytesRead = bis.read(buff, 0, buff.length))) { bos.write(buff, 0, bytesRead); } } catch (Exception e) { e.printStackTrace(); } finally { if (bis != null) bis.close(); if (bos != null) bos.close(); } } /** * 將第一個字母轉換為大寫字母並和get拼合成方法 * * @param origin * @return */ private static String toUpperCaseFirstOne(String origin) { StringBuffer sb = new StringBuffer(origin); sb.setCharAt(0, Character.toUpperCase(sb.charAt(0))); sb.insert(0, "get"); return sb.toString(); } }

提一下前臺呼叫

<a href="#" onclick="exportData()" class="easyui-linkbutton" iconCls="icon-save">匯出</a>

js

/**
 * 匯出功能
 */
function exportData() {
    var exportURL=basePath + "/dustDataSelAction.do?action=export";
    //var path = encodeURI('${sd_graduateThesis.path}', "UTF-8");
    var xhLx=$("#xhLxComb").combobox('getValue');
    var gn=$("#gnCombobox").combobox('getValue');
    var start=$('#startTime').datetimebox('getValue');

    //使用form表單來發送請求 1.method屬性用來設定請求的型別——post還是get 2.action屬性用來設定請求路徑。
    var form = $("<form>");// 定義一個form表單
    form.attr("style", "display:none");
    form.attr("target", "");
    form.attr("method", "post"); // 請求型別
    form.attr("action", exportURL); // 請求地址

    var input1 = $("<input>");
    input1.attr("type", "hidden");
    input1.attr("name", "xhLxComb");
    input1.attr("value", xhLx);
    form.append(input1);
    var input2 = $("<input>");
    input2.attr("type", "hidden");
    input2.attr("name", "gnId");
    input2.attr("value", gn);
    form.append(input2);
    var input3 = $("<input>");
    input3.attr("type", "hidden");
    input3.attr("name", "startTime");
    input3.attr("value", start);
    form.append(input3);

    $("body").append(form);// 將表單放置在web中
    form.submit();// 表單提交
    form.remove();
}

over了

注意:

1.如果報這個錯誤

 getWriter() has already been called for this response(異常解決)

通過response.reset(); 重新整理可能存在一些未關閉的getWriter().
我已經在程式碼寫出來了,再寫一遍是為了提醒自己不要再犯這樣的錯誤
2.用這個需要匯入poi的jar檔案,官網官網:http://poi.apache.org
這裡寫圖片描述