1. 程式人生 > >java poi匯出excel 工具

java poi匯出excel 工具

基本上每個系統或多或少都有一些匯出功能,我之前做的系統是針對每個功能定製一個匯出,而且我看網上的也大多是這麼做的,這樣就存在一個程式碼冗餘的問題,而且增加工作量,今天整理了一下,系統中所有的匯出都可以引用(注意我這裡說的是excel,word的暫時還沒整理),並且支援匯出圖片,上程式碼。

1. jar包準備

如果你是新手請參考 https://blog.csdn.net/fulishafulisha/article/details/80152805 ,如果使用的maven

<dependency>
         <groupId>org.apache.poi</groupId
> <artifactId>poi</artifactId> <version>3.10-FINAL</version> </dependency> <dependency> <groupId>org.apache.poi</groupId> <artifactId>poi-ooxml</artifactId> <version>3.10-FINAL</version
> </dependency>

2. 工具類 

import lombok.extern.slf4j.Slf4j;
import org.apache.poi.hssf.usermodel.*;
import org.apache.poi.hssf.util.HSSFColor;
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; import javax.servlet.http.HttpServletResponse; import java.io.*; import java.math.BigDecimal; import java.text.DecimalFormat; import java.text.SimpleDateFormat; import java.util.ArrayList; import java.util.Arrays; import java.util.Date; import java.util.List; import java.util.regex.Matcher; /** * Excel工具類 * * @author yunfei */ @Slf4j public class ExeclUtil { //正則判斷是否是數字 private static Pattern p = Pattern.compile("^//d+(//.//d+)?$"); /** * @param title * @param headers * @param dataset */ public static InputStream exportExcel(String title, String[] headers, List<Object[]> dataset) { InputStream is; ByteArrayOutputStream os = new ByteArrayOutputStream(); // 宣告一個工作薄 HSSFWorkbook workbook = new HSSFWorkbook(); // 生成一個表格 HSSFSheet sheet = workbook.createSheet(title); // 設定表格預設列寬度為15個位元組 sheet.setDefaultColumnWidth(15); // 生成一個樣式 HSSFCellStyle style = workbook.createCellStyle(); // 設定這些樣式 style.setFillForegroundColor(HSSFColor.SKY_BLUE.index); style.setFillPattern(HSSFCellStyle.SOLID_FOREGROUND); style.setBorderBottom(HSSFCellStyle.BORDER_THIN); style.setBorderLeft(HSSFCellStyle.BORDER_THIN); style.setBorderRight(HSSFCellStyle.BORDER_THIN); style.setBorderTop(HSSFCellStyle.BORDER_THIN); style.setAlignment(HSSFCellStyle.ALIGN_CENTER); // 生成一個字型 HSSFFont font = workbook.createFont(); font.setColor(HSSFColor.VIOLET.index); font.setFontHeightInPoints((short) 12); font.setBoldweight(HSSFFont.BOLDWEIGHT_BOLD); // 把字型應用到當前的樣式 style.setFont(font); // 生成並設定另一個樣式 HSSFCellStyle style2 = workbook.createCellStyle(); style2.setFillForegroundColor(HSSFColor.LIGHT_YELLOW.index); style2.setFillPattern(HSSFCellStyle.SOLID_FOREGROUND); style2.setBorderBottom(HSSFCellStyle.BORDER_THIN); style2.setBorderLeft(HSSFCellStyle.BORDER_THIN); style2.setBorderRight(HSSFCellStyle.BORDER_THIN); style2.setBorderTop(HSSFCellStyle.BORDER_THIN); style2.setAlignment(HSSFCellStyle.ALIGN_CENTER); style2.setVerticalAlignment(HSSFCellStyle.VERTICAL_CENTER); // 生成另一個字型 HSSFFont font2 = workbook.createFont(); font2.setBoldweight(HSSFFont.BOLDWEIGHT_NORMAL); // 把字型應用到當前的樣式 style2.setFont(font2); // 宣告一個畫圖的頂級管理器 HSSFPatriarch patriarch = sheet.createDrawingPatriarch(); // 定義註釋的大小和位置,詳見文件 HSSFComment comment = patriarch.createComment(new HSSFClientAnchor(0, 0, 0, 0, (short) 4, 2, (short) 6, 5)); // 設定註釋內容 comment.setString(new HSSFRichTextString("可以在POI中添加註釋!")); // 設定註釋作者,當滑鼠移動到單元格上是可以在狀態列中看到該內容. comment.setAuthor("leno"); // 產生表格標題行 HSSFRow row = sheet.createRow(0); for (int i = 0; i < headers.length; i++) { HSSFCell cell = row.createCell(i); cell.setCellStyle(style); HSSFRichTextString text = new HSSFRichTextString(headers[i]); cell.setCellValue(text); } // 遍歷集合資料,產生資料行 int index = 0; for (Object[] o : dataset) { index++; row = sheet.createRow(index); for (int i = 0; i < o.length; i++) { HSSFCell cell = row.createCell(i); cell.setCellStyle(style2); try { Object value = o[i]; if (value == null) { value = ""; } // 判斷值的型別後進行強制型別轉換 String textValue = null; if (value instanceof Boolean) { boolean bValue = (Boolean) value; textValue = "男"; if (!bValue) { textValue = "女"; } } else if (value instanceof Date) { Date date = (Date) value; SimpleDateFormat sdf = new SimpleDateFormat("yyyy-MM-dd HH:mm:ss"); textValue = sdf.format(date); } else if (value instanceof byte[]) { // 有圖片時,設定行高為60px; row.setHeightInPoints(60); // 設定圖片所在列寬度為80px,注意這裡單位的一個換算 sheet.setColumnWidth(i, (int) (35.7 * 80)); // sheet.autoSizeColumn(i); byte[] bsValue = (byte[]) value; HSSFClientAnchor anchor = new HSSFClientAnchor(0, 0, 1023, 255, (short) 7, index, (short) 7, index); anchor.setAnchorType(2); patriarch.createPicture(anchor, workbook.addPicture(bsValue, HSSFWorkbook.PICTURE_TYPE_JPEG)); } else { // 其它資料型別都當作字串簡單處理 textValue = value.toString(); } // 如果不是圖片資料,就利用正則表示式判斷textValue是否全部由數字組成 if (textValue != null) { Matcher matcher = p.matcher(textValue); if (matcher.matches()) { // 是數字當作double處理 cell.setCellValue(Double.parseDouble(textValue)); } else { HSSFRichTextString richString = new HSSFRichTextString( textValue); HSSFFont font3 = workbook.createFont(); font3.setColor(HSSFColor.BLUE.index); richString.applyFont(font3); cell.setCellValue(richString); } } } catch (Exception e) { log.error(e.getMessage(), e); e.printStackTrace(); } finally { // 清理資源 } } } try { workbook.write(os); } catch (IOException e) { log.error(e.getMessage(), e); e.printStackTrace(); } is = new ByteArrayInputStream(os.toByteArray()); return is; } /** * 匯出excel * * @param response * @param headArray 表頭 * @param contentList 內容 * @param fileName 檔名 * @throws Exception */ public static void exportExcel(HttpServletResponse response, String[] headArray, List contentList, String fileName) throws Exception { // 讀到流中 InputStream inStream = exportExcel(fileName, headArray, contentList); // 設定輸出的格式 // response.reset(); response.setContentType("application/octet-stream"); response.addHeader("Access-Control-Expose-Headers","Content-Disposition"); response.addHeader("Content-Disposition", "attachment; filename=\"" + fileName + "\""); // response.addHeader("Access-Control-Allow-Credentials","true"); // 迴圈取出流中的資料 byte[] b = new byte[100]; int len; try { while ((len = inStream.read(b)) > 0) { response.getOutputStream().write(b, 0, len); } inStream.close(); } catch (IOException e) { log.error(e.getMessage(), e); e.printStackTrace(); } } }

3. 測試使用

  public void exportTransaction(String userId, String orderNo, String dateFrom, String dateEnd, String orderStatus, String payment, String userOrAgentId, HttpServletResponse response) throws Exception {
        ResultData<List<OrderViewVO>> resultData = umrahApi.getOrderList(userId, orderNo, dateFrom, dateEnd, orderStatus, payment, userOrAgentId);
        List<OrderViewVO> orderViewVOList = resultData.getData();
        log.info("Order資料共:{} 條",orderViewVOList.size());
        String[] headers = {"Order Number","Book Date","User ID","Order Status","Departure Date"};
        List<Object[]> objects = new ArrayList<>();
        for (OrderViewVO entity : orderViewVOList) {
            Object[] o = {entity.getOrderNumber,...省略 };
            objects.add(o);
        }

        ExeclUtil.exportExcel(response, headers, objects, "transactions.xls");
    }