1. 程式人生 > >利用poi將資料寫入到excel

利用poi將資料寫入到excel

import org.apache.poi.hssf.usermodel.*; import org.apache.poi.hssf.util.HSSFColor; import java.io.FileNotFoundException; import java.io.FileOutputStream; import java.io.IOException; import java.io.OutputStream; import java.text.SimpleDateFormat; import java.util.Date; /** * Created by youlinmin on 2017/4/8. */ public class TransToExcel { /** * 匯出excel檔案 * @param title 表sheet的名字 * @param headers 表頭 * @param dataList 正文單元格 * @param out 輸出流 */ public void exporteExcel(String title,String[] headers,String[][] dataList,OutputStream out){ HSSFWorkbook workBook = new HSSFWorkbook(); createSheet(title, headers, dataList, workBook); createSheet(title+"2", headers, dataList, workBook); try { workBook.write(out); }catch (IOException e){ System.out
.println("寫入檔案失敗"+e.getMessage()); } } /** * 建立sheet * @param title sheet的名字 * @param headers 表頭 * @param dataList 正文單元格 */ private void createSheet(String title, String[] headers, String[][] dataList, HSSFWorkbook workBook) { HSSFSheet sheet = workBook.createSheet(title); // sheet.setDefaultColumnWidth(15); //設定表頭和普通單元格的格式 HSSFCellStyle headStyle = setHeaderStyle(workBook); HSSFCellStyle bodyStyle = setBodyStyle(workBook); createBody(dataList, sheet, bodyStyle); createHeader(headers, sheet, headStyle); } /** * 建立正文單元格 * @param dataList 資料陣列 * @param sheet 表 * @param bodyStyle 單元格格式 */ private void createBody(String[][] dataList, HSSFSheet sheet, HSSFCellStyle bodyStyle) { for (int a=0;a<dataList.length;a++){ HSSFRow row = sheet.createRow(a+1); for(int j=0;j<dataList[a].length;j++){ HSSFCell cell = row.createCell(j); cell.setCellStyle(bodyStyle); HSSFRichTextString textString = new HSSFRichTextString(dataList[a][j]); cell.setCellValue(textString); } } } /** * 建立表頭 * @param headers 表頭 * @param sheet 表 * @param headStyle 表頭格式 */ private void createHeader(String[] headers, HSSFSheet sheet, HSSFCellStyle headStyle) { HSSFRow row = sheet.createRow(0); for (int i=0;i<headers.length;i++){ HSSFCell cell = row.createCell(i); cell.setCellStyle(headStyle); HSSFRichTextString textString = new HSSFRichTextString(headers[i]); cell.setCellValue(textString); sheet.autoSizeColumn((short)i); } } /** * 設定正文單元格格式 * @param workBook * @return */ private HSSFCellStyle setBodyStyle(HSSFWorkbook workBook) { HSSFCellStyle style2 = workBook.createCellStyle(); style2.setFillForegroundColor(HSSFColor.WHITE.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_LEFT
); HSSFFont font2 = workBook.createFont();