利用poi进行数据的excel导出
生活随笔
收集整理的這篇文章主要介紹了
利用poi进行数据的excel导出
小編覺得挺不錯的,現在分享給大家,幫大家做個參考.
2019獨角獸企業重金招聘Python工程師標準>>>
添加maven依賴:
<!-- poi --> <dependency><groupId>org.apache.poi</groupId><artifactId>poi-ooxml</artifactId><version>3.17-beta1</version> </dependency><!-- fast json --> <dependency> <groupId>com.alibaba</groupId><artifactId>fastjson</artifactId><version>1.2.31</version> </dependency>主要代碼:
import com.alibaba.fastjson.JSON; import com.alibaba.fastjson.JSONArray; import com.alibaba.fastjson.JSONObject; import com.liyang.entity.UserEntity; import org.apache.poi.hssf.usermodel.HSSFFont; import org.apache.poi.hssf.util.HSSFColor; import org.apache.poi.ss.usermodel.Cell; import org.apache.poi.ss.usermodel.CellStyle; import org.apache.poi.ss.usermodel.DataFormat; import org.apache.poi.ss.usermodel.Font; 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.ss.util.CellRangeAddress; import org.apache.poi.xssf.usermodel.XSSFWorkbook;import javax.servlet.http.HttpServletResponse; import java.io.BufferedInputStream; import java.io.BufferedOutputStream; import java.io.ByteArrayInputStream; import java.io.ByteArrayOutputStream; import java.io.FileOutputStream; import java.io.IOException; import java.util.Arrays; import java.util.List;/** * 導出excel工具 * * @author 李陽 * @mail ly_triangle@126.com * 15002992382 * 2017-07-24 */ public class ExcelUtil {/** * 根據給定的數據在前端頁面導出excel * * @param fileName 文件名 * @param wb 工作簿 * @param response * @throws IOException */ public static void exportDatasExcel(String fileName, Workbook wb, HttpServletResponse response) throws IOException {????????//清空前端緩存 ????????response.reset(); ????????//指定前端文件mime類型 response.setContentType("application/vnd.ms-excel;charset=utf-8");response.setHeader("Content-Disposition", "attachment;fileName="+ new String(replaceSpecialChars(fileName).getBytes(), "iso8859-1")+ ".xlsx");//字節數組輸出流 ByteArrayOutputStream out = new ByteArrayOutputStream();//將工作簿寫進字節數組輸出流中 wb.write(out);//創建字節數組輸入流,將輸出流中的數據寫進該輸入流中,最后創建輸入流的緩沖流,便于讀取數據 BufferedInputStream bufferIn = new BufferedInputStream(new ByteArrayInputStream(out.toByteArray()));//獲得response輸出流,并獲得輸出流的緩沖流,便于寫入數據 BufferedOutputStream bufferOut = new BufferedOutputStream(response.getOutputStream());//每次輸出文件1000字節長度數據到輸出流 byte[] buffer = new byte[1000];int bytesRead;//讀取輸入緩沖流中的數據,經過緩沖輸出流發送給前端下載 while (-1 != (bytesRead = bufferIn.read(buffer))) {bufferOut.write(buffer, 0, bytesRead);}bufferOut.flush();bufferIn.close();bufferOut.close();}/** * 創建excel表格(記錄性結果) * * @param titles 標題集合 * @param keys key值集合,用于讀取json對象中的數據 * @param objects 數據對象集合 * @return */ private static Workbook buildWorkbook(List<String> titles, List<String> keys, List<Object> objects, String fileName) {//創建工作簿 Workbook wb = new XSSFWorkbook(); //or new HSSFWorkbook(); //創建表格 Sheet sheet = wb.createSheet(replaceSpecialChars(fileName));//第一行 Row row = sheet.createRow(0);//第二行 Row row1 = sheet.createRow(1);//創建數據單元格樣式 CellStyle style = creatStyle(wb);//創建標題單元格樣式CellStyle titleStyle = creatTitleStyle(wb);Cell cell;Cell cell1;//遍歷標題,標題占兩行 for (int t = 0; t < titles.size(); t++) {//創建標題單元格并設置標題單元格的值 cell = row.createCell(t);cell.setCellValue(titles.get(t));//創建第二行單元格 cell1 = row1.createCell(t);//合并上下單元格(標題占兩行) sheet.addMergedRegion(new CellRangeAddress(0, 1, t, t));//對單元格使用樣式 cell.setCellStyle(titleStyle );cell1.setCellStyle(titleStyle );}//將對象集合轉換成json對象數組 JSONArray array = JSON.parseArray(JSON.toJSONString(objects));//遍歷json對象數組,將數據寫進excel中 for (int r = 2; r < array.size() + 2; r++) {JSONObject o = array.getJSONObject(r - 2);//創建行 row = sheet.createRow(r);//創建行單元格,并賦值 for (int c = 0; c < keys.size(); c++) {String value = o.get(keys.get(c)) == null ? "" : o.get(keys.get(c)).toString();cell = row.createCell(c);cell.setCellValue(value);cell.setCellStyle(style);}}// 最后一列寬自適應sheet.autoSizeColumn(titles.size()-1);//獲得工作簿 return wb;}創建復雜excel表格(非記錄性數據,需要一定模板):
/** * 動態生成復雜excel * * @param rowSize 行數 * @param columnSize 列數 * @param models 單元格實例集合(每一個單元格(包括合并的單元格)起止行列四個索引和單元格的值) * @param fileName 文件名 * @return */ public static Workbook buildWorkbook2(Integer rowSize, Integer columnSize, List<CellModel> models, String fileName) {Workbook wb = new XSSFWorkbook();Sheet sheet = wb.createSheet(replaceSpecialChars(fileName));CellStyle style = creatStyle(wb);CellStyle titleStyle = creatTitleStyle(wb);Row row;Cell cell;//創建空表格 for (int r = 0; r < rowSize; r++) {row = sheet.createRow(r);for (int c = 0; c < columnSize; c++) {cell = row.createCell(c);if (0 == r || 1 == r) {cell.setCellStyle(titleStyle);} else {cell.setCellStyle(style);}}}//單元格賦值并合并單元格 models.forEach(c -> {Integer rowBegin = c.getRowBegin();Integer rowEnd = c.getRowEnd();Integer columnBegin = c.getColumnBegin();Integer columnEnd = c.getColumnEnd();sheet.getRow(rowBegin).getCell(columnBegin).setCellValue(c.getValue().toString());if (rowBegin.intValue() != rowEnd.intValue() || columnBegin.intValue() != columnEnd.intValue())sheet.addMergedRegion(new CellRangeAddress(rowBegin, rowEnd, columnBegin, columnEnd));});short height = sheet.getDefaultRowHeight();sheet.setDefaultRowHeight((short) (height * 1.7));sheet.setDefaultColumnWidth(15);return wb; }單元格對象:
public class CellModel {private Object value = ""; //單元格值 private Integer rowBegin; //開始行索引 private Integer rowEnd; //結束行索引 private Integer columnBegin; //開始列索引 private Integer columnEnd; //結束列索引.....略創建標題樣式:
/** * create title style * @param wb * @return */ private static CellStyle creatTitleStyle(Workbook wb) {Font font = wb.createFont();font.setFontHeightInPoints((short) 12);font.setFontName("黑體");font.setBold(true);CellStyle titleStyle = wb.createCellStyle();titleStyle.setAlignment(HorizontalAlignment.CENTER);titleStyle.setVerticalAlignment(VerticalAlignment.CENTER);titleStyle.setBorderTop(BorderStyle.THIN);titleStyle.setBorderBottom(BorderStyle.THIN);titleStyle.setBorderLeft(BorderStyle.THIN);titleStyle.setBorderRight(BorderStyle.THIN);//背景色titleStyle.setFillForegroundColor(HSSFColor.HSSFColorPredefined.SEA_GREEN.getIndex());titleStyle.setFillPattern(FillPatternType.SOLID_FOREGROUND);titleStyle.setFont(font);return titleStyle; }創建數據樣式:
private static CellStyle creatStyle(Workbook wb) {Font font = wb.createFont();//字號font.setFontHeightInPoints((short) 12);//字體font.setFontName("宋體");?? //斜體//font.setItalic(true);//加粗//font.setBoldweight(HSSFFont.BOLDWEIGHT_BOLD);//創建樣式CellStyle style = wb.createCellStyle();// 給樣式指定字體style.setFont(font);//縱橫向居中style.setAlignment(HorizontalAlignment.CENTER);style.setVerticalAlignment(VerticalAlignment.CENTER);//四周邊框style.setBorderTop(BorderStyle.THIN);style.setBorderBottom(BorderStyle.THIN);style.setBorderLeft(BorderStyle.THIN);style.setBorderRight(BorderStyle.THIN);return style; }文件名特殊字符處理(特殊字符統一用空格替換)
private static String replaceSpecialChars(String fileName) {return fileName.replaceAll(":", " ").replaceAll(":", " ").replaceAll("?", " ").replaceAll("\\?", " ").replaceAll("\\*", " ").replaceAll("]", " ").replaceAll("\\[", " ").replaceAll("“", " ").replaceAll("”", " ").replaceAll("\"", " ").replaceAll("\\|", " ").replaceAll(">", " ").replaceAll("<", " ").replaceAll("\\\\", " ").replaceAll("/", " "); }測試1(記錄性結果):
/*** test */ public static void main(String[] args) throws IOException {//構造數據對象集合 List list = Arrays.asList(new UserEntity("kevin", "lee", 5),new UserEntity("david", "lee", null),new UserEntity("kavin", "", 6),new UserEntity("kavein", "lee", 65));//構造標題和key值列表,生成工作簿 Workbook wb = buildWorkbook(Arrays.asList("姓名", "全名", "年齡"),Arrays.asList("stageName", "fullName", "sex"), list);//生成服務器本地文件,如需輸出到前端,只需要調用exportDatasExcel方法即可 FileOutputStream fileOut = new FileOutputStream("dataExcel.xlsx");wb.write(fileOut);fileOut.close();wb.close();}測試2(復雜結果):
public static void main(String[] args) throws IOException {//構造數據對象集合 List list = new ArrayList();list.add(new CellModel("標題", 0, 1, 0, 3)); list.add(new CellModel("購買渠道", 2, 26, 0, 0));list.add(new CellModel("微信", 2, 13, 1, 1));list.add(new CellModel("網站", 14, 26, 1, 1)); list.add(new CellModel("微信平臺名稱", 2, 3, 2, 3));list.add(new CellModel("大秦帝國", 4, 13, 2, 3));list.add(new CellModel("網站平臺名稱", 14, 15, 2, 3));list.add(new CellModel("餓狼傳說", 16, 26, 2, 3));//構造標題和key值列表,生成工作簿 Workbook wb = buildWorkbook2(27, 5, list, "domo");//生成服務器本地文件,如需輸出到前端,只需要調用exportDatasExcel方法即可 FileOutputStream fileOut = new FileOutputStream("domo.xlsx");wb.write(fileOut);fileOut.close();wb.close(); }測試結果:
記錄性結果excel:
復雜excel結果:
?
轉載于:https://my.oschina.net/kevin2kelly/blog/1486059
總結
以上是生活随笔為你收集整理的利用poi进行数据的excel导出的全部內容,希望文章能夠幫你解決所遇到的問題。
- 上一篇: Mockito对final类型和方法的支
- 下一篇: 几个关于tableView的问题解决方式