Java導出excel工具類
web開發中,一個系統的普通需求也包括導出excel,一般采用POI做統計報表導出excel。
導出excel工具類:
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.HSSFRichTextString; import org.apache.poi.hssf.usermodel.HSSFRow; import org.apache.poi.hssf.usermodel.HSSFSheet; import org.apache.poi.hssf.usermodel.HSSFWorkbook; public class ExportExcel { private ExportExcel() { super(); } public static void exportExcel(List<Object> list, Map<Integer, Long> map, String[] titles) throws IOException { // 創建Excel文檔 HSSFWorkbook hwb = new HSSFWorkbook(); // sheet 對應一個工作頁 HSSFSheet sheet = hwb.createSheet("exportReport"); int colNum = titles.length; // 創建第一行 HSSFRow firstrow = sheet.createRow(0); HSSFCell[] firstcell = new HSSFCell[colNum]; for (int col = 0; col < colNum; col++) { firstcell[col] = firstrow.createCell(col); firstcell[col].setCellValue(new HSSFRichTextString(titles[col])); } // 插入記錄 int rowNum = map.size(); for (int i = 0; i < rowNum; i++) { // 從第二行開始 HSSFRow row = sheet.createRow(i + 1); // 插入list中的字段 for (int col = 0; col < colNum - 2; col++) { HSSFCell cell = row.createCell(col); cell.setCellValue(list.get(col).toString()); } // 插入月份或日期 row.createCell(colNum - 2).setCellValue(i + 1); // 插入總量 row.createCell(colNum - 1).setCellValue(map.get(i + 1)); } String fileName = titles[1].substring(0, 2); if (colNum == 4) { fileName += list.get(0) + "_" + list.get(1) + "年_年度報表"; } else if (colNum == 5) { fileName += list.get(0) + "_" + list.get(1) + "年" + list.get(2) + "月_月度報表"; } // 創建文件輸出流,準備輸出電子表格 OutputStream out = new FileOutputStream("../webapps/UsedMallMinaServer/files/" + fileName + ".xls"); hwb.write(out); out.close(); } }
本文由用戶 pooi 自行上傳分享,僅供網友學習交流。所有權歸原作者,若您的權利被侵害,請聯系管理員。
轉載本站原創文章,請注明出處,并保留原始鏈接、圖片水印。
本站是一個以用戶分享為主的開源技術平臺,歡迎各類分享!