一、使用java
String toFileName = "E:\\sheet1.xlsx"; String fromFileName = "E:\\sheet2.xlsx"; MemoryToExcel memoryToExcel = new MemoryToExcel(); memoryToExcel.mergeExcel(toFileName, 1, fromFileName, 0); // String fileName = "E:\\test.xlsx"; // String sheetName = "Test"; // // Map<Integer, FrameworkEnums.EnumDBDataType> dataTypeByColumn = // new HashMap<Integer, EnumDBDataType>(); // dataTypeByColumn.put(1, EnumDBDataType.Int); // dataTypeByColumn.put(2, EnumDBDataType.Int); // dataTypeByColumn.put(3, EnumDBDataType.Date); // dataTypeByColumn.put(4, EnumDBDataType.DateTime); // // Map<Integer, String> dataFormatByColumn = new HashMap<Integer, // String>(); // //dataFormatByColumn.put(2, "0.00%"); // dataFormatByColumn.put(3, "yyyy-mm-dd"); // dataFormatByColumn.put(4, "yyyy-mm-dd hh:mm:ss"); // // Object[][] data = new Object[100][10]; // // for (int i = 0; i < 100; i++) { // for (int j = 0; j < 10; j++) { // if (j == 1) { // data[i][j] = i; // } else if (j == 2) { // data[i][j] = i + 0.6; // } else if (j == 3) { // data[i][j] = new Date(); // } else if (j == 4) { // data[i][j] = new Date(); // } else { // data[i][j] = "" + i + "+" + j; // } // } // } // // MemoryToExcel memoryToExcel = new MemoryToExcel(); // memoryToExcel.setFileName(fileName); // memoryToExcel.setSheetName(sheetName); // memoryToExcel.setTopSkipRows(2); // memoryToExcel.setSourceData(data); // memoryToExcel.setDataTypeByColumn(dataTypeByColumn); // memoryToExcel.setDataFormatByColumn(dataFormatByColumn); // memoryToExcel.start(); // System.out.println("寫數據結束!"); // // memoryToExcel.setWrapCellData(0, 0, 0, "報表測試"); // for (int i = 0; i < 10; i++) { // memoryToExcel.setWrapCellData(0, 1, i, "累計\r\n外呼量" + i); // } // System.out.println("設置標題和列名結束!"); // memoryToExcel.setColumnWidth(0, 0, 9, 10); // memoryToExcel.setRowHeight(0, 1, 2, (short)15); // memoryToExcel.setAutoFit(0, 0, 2); // System.out.println("設置自適應結束!"); // Color color = new Color(54, 201, 201); // memoryToExcel.setBackgroundColor(0, 1, 1, 0, 10, color); // System.out.println("設置背景色結束!"); // // memoryToExcel.setMerge(0, 0, 0, 0, 9); // System.out.println("設置單元格合併結束!"); // // Font font = new Font("宋體", Font.BOLD, 12); // color = new Color(255, 0, 0); // memoryToExcel.setFont(0, 0, 1, 0, 1, font, color); // font = new Font("宋體", Font.BOLD, 10); // memoryToExcel.setFont(0, 1, 1, 0, 10, font); // font = new Font("宋體", Font.PLAIN, 9); // memoryToExcel.setFont(0, 2, 100, 0, 10, font); // System.out.println("設置字體結束!"); // // memoryToExcel.setBorder(0, 0, 100 + 2, 0, 10); // System.out.println("設置Border結束!"); // // memoryToExcel.setAlignment(0, 0, 100 + 2, 0, 10, // (short) 2, (short) 1); // System.out.println("設置對齊方式結束!"); // System.out.println("導出成功"); } catch (Exception e) { System.out.println(String.format("導出失敗,%s", e.getMessage())); } System.exit(0);
二、核心代碼apache
package nankang.test; import java.io.FileInputStream; import java.io.FileOutputStream; import java.io.InputStream; import java.io.OutputStream; import java.text.SimpleDateFormat; import java.util.Date; import java.util.HashMap; import java.util.Map; 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.streaming.SXSSFWorkbook; import org.apache.poi.xssf.usermodel.XSSFCellStyle; import org.apache.poi.xssf.usermodel.XSSFColor; import org.apache.poi.xssf.usermodel.XSSFFont; import org.apache.poi.xssf.usermodel.XSSFWorkbook; public class MemoryToExcel { private String m_FileName; private String m_SheetName; private int m_TopSkipRows = 0; private int m_TopSkipCols = 0; private int m_DataType2SartRow = 0; private Map<Integer, FrameworkEnums.EnumDBDataType> m_DataTypeByColumn = new HashMap<Integer, FrameworkEnums.EnumDBDataType>(); private Map<Integer, String> m_DataFormatByColumn = new HashMap<Integer, String>(); private Map<Integer, FrameworkEnums.EnumDBDataType> m_DataTypeByColumn2 = new HashMap<Integer, FrameworkEnums.EnumDBDataType>(); private Map<Integer, String> m_DataFormatByColumn2 = new HashMap<Integer, String>(); private Object[][] m_SourceData; /** * 返回 文件名稱 * * @return 文件名稱 */ public String getFileName() { return m_FileName; } /** * 設置文件名 * * @param fileName * 文件名稱 */ public void setFileName(String fileName) { m_FileName = fileName; } public String getSheetName() { return m_SheetName; } public void setSheetName(String sheetName) { m_SheetName = sheetName; } public int getTopSkipRows() { return m_TopSkipRows; } public void setTopSkipRows(int topSkipRows) { m_TopSkipRows = topSkipRows; } public int getTopSkipCols() { return m_TopSkipCols; } public void setTopSkipCols(int topSkipCols) { m_TopSkipCols = topSkipCols; } public int getDataType2SartRow() { return m_DataType2SartRow; } public void setDataType2SartRow(int mDataType2SartRow) { m_DataType2SartRow = mDataType2SartRow; } public Map<Integer, FrameworkEnums.EnumDBDataType> getDataTypeByColumn() { return m_DataTypeByColumn; } public void setDataTypeByColumn( Map<Integer, FrameworkEnums.EnumDBDataType> dataTypeByColumn) { m_DataTypeByColumn = dataTypeByColumn; } public Map<Integer, String> getDataFormatByColumn() { return m_DataFormatByColumn; } public void setDataFormatByColumn(Map<Integer, String> dataFormatByColumn) { m_DataFormatByColumn = dataFormatByColumn; } public Map<Integer, FrameworkEnums.EnumDBDataType> getDataTypeByColumn2() { return m_DataTypeByColumn2; } public void setDataTypeByColumn2( Map<Integer, FrameworkEnums.EnumDBDataType> mDataTypeByColumn2) { m_DataTypeByColumn2 = mDataTypeByColumn2; } public Map<Integer, String> getDataFormatByColumn2() { return m_DataFormatByColumn2; } public void setDataFormatByColumn2(Map<Integer, String> mDataFormatByColumn2) { m_DataFormatByColumn2 = mDataFormatByColumn2; } public Object[][] getSourceData() { return m_SourceData; } public void setSourceData(Object[][] sourceData) { m_SourceData = sourceData; } /** * 生成Excel文件 * * @throws Exception */ public void start() throws Exception { try { // 用SXSSFWorkbook設置緩存數據,處理批量寫入 Workbook workbook = new SXSSFWorkbook(1000); Sheet sheet = null; if (m_SheetName.isEmpty()) { sheet = workbook.createSheet(); } else { sheet = workbook.createSheet(m_SheetName); } // 寫入數據 for (int rIndex = 0; rIndex < m_SourceData.length; rIndex++) { int dataRIndex = rIndex + m_TopSkipRows; Row row = sheet.createRow(dataRIndex); for (int cIndex = 0; cIndex < m_SourceData[rIndex].length; cIndex++) { int dataCIndex = cIndex + m_TopSkipCols; Map<Integer, FrameworkEnums.EnumDBDataType> dataTypeByColumn = m_DataTypeByColumn; Map<Integer, String> dataFormatByColumn = m_DataFormatByColumn; if ((m_DataType2SartRow > 0) && (dataRIndex >= m_DataType2SartRow)) { dataTypeByColumn = m_DataTypeByColumn2; dataFormatByColumn = m_DataFormatByColumn2; } Cell cell = row.createCell(dataCIndex); Object value = m_SourceData[rIndex][cIndex]; if (value == null) { continue; } // 設置但單元格值樣式 String dataFormat = dataFormatByColumn.get(dataCIndex); if ((dataFormat != null) && ("".equals(dataFormat) == false)) { CellStyle style = workbook.createCellStyle(); DataFormat format = workbook.createDataFormat(); style.setDataFormat(format.getFormat(dataFormat)); cell.setCellStyle(style); } // 設置單元格的值和值類型 FrameworkEnums.EnumDBDataType dataType = dataTypeByColumn .get(dataCIndex); if (dataType != null) { switch (dataType) { case AnsiStringFixedLength: case AnsiString: case String: case StringFixedLength: cell.setCellValue(value.toString()); break; case Int: int intVal = 0; try { intVal = Integer.parseInt(value.toString()); } catch (Exception e) { try { double tmpVal = Double.parseDouble(value .toString()); intVal = (int) tmpVal; } catch (Exception ex) { String .format( "轉換成int失敗,Row:%s,Column:%s,Message:%s!", rIndex, cIndex, e .getMessage()); } } cell.setCellValue(intVal); break; case Double: double doubleVal = 0.0d; try { doubleVal = Double .parseDouble(value.toString()); } catch (Exception e) { throw new Exception( String .format( "轉換成double失敗,Row:%s,Column:%s,Message:%s!", rIndex, cIndex, e .getMessage())); } cell.setCellValue(doubleVal); break; case Float: float floatVal = 0.0f; try { floatVal = Float.parseFloat(value.toString()); } catch (Exception e) { throw new Exception( String .format( "轉換成float失敗,Row:%s,Column:%s,Message:%s!", rIndex, cIndex, e .getMessage())); } cell.setCellValue(floatVal); break; case Long: long longVal = 0l; try { longVal = Long.parseLong(value.toString()); } catch (Exception e) { throw new Exception( String .format( "轉換成long失敗,Row:%s,Column:%s,Message:%s!", rIndex, cIndex, e .getMessage())); } cell.setCellValue(longVal); break; case Short: short shortVal = (short) 0; try { shortVal = Short.parseShort(value.toString()); } catch (Exception e) { throw new Exception( String .format( "轉換成short失敗,Row:%s,Column:%s,Message:%s!", rIndex, cIndex, e .getMessage())); } cell.setCellValue(shortVal); break; case Date: SimpleDateFormat simpleDateFormat = new SimpleDateFormat( "yyyy-MM-dd"); Date dateVal = null; try { String dateString = simpleDateFormat .format(value); dateVal = simpleDateFormat.parse(dateString); } catch (Exception e) { throw new Exception( String .format( "轉換成Date失敗,Row:%s,Column:%s,Message:%s!", rIndex, cIndex, e .getMessage())); } cell.setCellValue(dateVal); break; case DateTime: case FullDateTime: simpleDateFormat = new SimpleDateFormat( "yyyy-MM-dd HH:mm:ss"); dateVal = null; try { String dateString = simpleDateFormat .format(value); dateVal = simpleDateFormat.parse(dateString); } catch (Exception e) { throw new Exception( String .format( "轉換成DateTime失敗,Row:%s,Column:%s,Message:%s!", rIndex, cIndex, e .getMessage())); } cell.setCellValue(dateVal); break; default: cell.setCellValue(value.toString()); break; } } else { cell.setCellValue(value.toString()); } } } // 寫入文件 OutputStream outputStream = new FileOutputStream(m_FileName); workbook.write(outputStream); outputStream.close(); } catch (Exception e) { throw new Exception(String.format("start:%s", e.getMessage())); } } /** * 設置單元格的值(先執行Start方法) * * @param sheetIndex * Sheet的索引,從0開始 * @param row * 行索引 * @param col * 列索引 * @param value * 值(暫時只支持字符串) * @throws Exception */ public void setCellData(int sheetIndex, int row, int col, String value) throws Exception { try { InputStream inputStream = new FileInputStream(m_FileName); XSSFWorkbook workbook = new XSSFWorkbook(inputStream); inputStream.close(); Sheet sheet = workbook.getSheetAt(sheetIndex); Row mRow = sheet.getRow(row); if (mRow == null) { mRow = sheet.createRow(row); } Cell mCell = mRow.createCell(col); mCell.setCellValue(value); // 寫入文件,採用分批寫入的方式進行寫入 OutputStream outputStream = new FileOutputStream(m_FileName); SXSSFWorkbook sXSSFWorkbook = new SXSSFWorkbook(workbook, 1000); sXSSFWorkbook.write(outputStream); outputStream.close(); } catch (Exception e) { throw new Exception(String.format("setCellData:%s", e.getMessage())); } } /** * 設置單元格的值,支持/n自動換行(先執行Start方法) * * @param sheetIndex * Sheet的索引,從0開始 * @param row * 行索引 * @param col * 列索引 * @param value * 值(暫時只支持字符串) * @throws Exception */ public void setWrapCellData(int sheetIndex, int row, int col, String value) throws Exception { try { InputStream inputStream = new FileInputStream(m_FileName); XSSFWorkbook workbook = new XSSFWorkbook(inputStream); inputStream.close(); Sheet sheet = workbook.getSheetAt(sheetIndex); Row mRow = sheet.getRow(row); if (mRow == null) { mRow = sheet.createRow(row); } Cell mCell = mRow.createCell(col); mCell.setCellValue(value); // 設置自動換行 CellStyle style = workbook.createCellStyle(); style.setWrapText(true); mCell.setCellStyle(style); // 寫入文件,採用分批寫入的方式進行寫入 OutputStream outputStream = new FileOutputStream(m_FileName); SXSSFWorkbook sXSSFWorkbook = new SXSSFWorkbook(workbook, 1000); sXSSFWorkbook.write(outputStream); outputStream.close(); } catch (Exception e) { throw new Exception(String.format("setWrapCellData:%s", e .getMessage())); } } /** * 設置單元格數據的水平垂直對齊方式(先執行Start方法) * * @param sheetIndex * Sheet的索引,從0開始 * @param startRow * 開始行,從0開始 * @param rowNum * 行數 * @param startCol * 開始列,從0開始 * @param colNum * 列數 * @param alignment * 水平展現方式 ALIGN_GENERAL = 0 ALIGN_LEFT = 1 ALIGN_CENTER = 2 * ALIGN_RIGHT = 3 ALIGN_FILL = 4 ALIGN_JUSTIFY = 5 * ALIGN_CENTER_SELECTION = 6 * @param verticalAlignment * 豎直展現方式 VERTICAL_TOP = 0 VERTICAL_CENTER = 1 VERTICAL_BOTTOM = * 2 VERTICAL_JUSTIFY = 3 * @throws Exception */ public void setAlignment(int sheetIndex, int startRow, int rowNum, int startCol, int colNum, short alignment, short verticalAlignment) throws Exception { try { InputStream inputStream = new FileInputStream(m_FileName); XSSFWorkbook workbook = new XSSFWorkbook(inputStream); inputStream.close(); Sheet sheet = workbook.getSheetAt(sheetIndex); // 設置單元格樣式 for (int rIndex = startRow; rIndex < startRow + rowNum; rIndex++) { Row row = sheet.getRow(rIndex); if (row == null) { row = sheet.createRow(rIndex); } for (int cIndex = startCol; cIndex < startCol + colNum; cIndex++) { Cell cell = row.getCell(cIndex); if (cell == null) { cell = row.createCell(cIndex); } CellStyle style = cell.getCellStyle(); // 判斷是否已經建立過 if (style.getIndex() == 0) { style = workbook.createCellStyle(); } style.setAlignment(alignment); style.setVerticalAlignment(verticalAlignment); cell.setCellStyle(style); } } // 寫入文件,採用分批寫入的方式進行寫入 OutputStream outputStream = new FileOutputStream(m_FileName); SXSSFWorkbook sXSSFWorkbook = new SXSSFWorkbook(workbook, 1000); sXSSFWorkbook.write(outputStream); outputStream.close(); } catch (Exception e) { throw new Exception(String .format("setAlignment:%s", e.getMessage())); } } /** * 設置單元格的字體及大小(先執行Start方法) * * @param sheetIndex * Excel索引,從0開始 * @param startRow * 開始行,從0開始 * @param rowNum * 設置的行數 * @param startCol * 開始列,從0開始 * @param colNum * 設置的列數 * @param font * 字體:TimesRoman, Courier, Arial等 風格:三個常量 lFont.PLAIN, Font.BOLD, * Font.ITALIC 字號:字的大小(磅數) 字體名稱和大小 BOLDWEIGHT_NORMAL = 400; * BOLDWEIGHT_BOLD = 700 * @throws Exception */ public void setFont(int sheetIndex, int startRow, int rowNum, int startCol, int colNum, java.awt.Font font) throws Exception { try { InputStream inputStream = new FileInputStream(m_FileName); XSSFWorkbook workbook = new XSSFWorkbook(inputStream); inputStream.close(); Font mFont = workbook.createFont(); mFont.setFontName(font.getFontName()); mFont.setFontHeightInPoints((short) font.getSize()); if (font.isBold() == true) { mFont.setBoldweight((short) 700); } else { mFont.setBoldweight((short) 400); } Sheet sheet = workbook.getSheetAt(sheetIndex); // 設置單元格樣式 for (int rIndex = startRow; rIndex < startRow + rowNum; rIndex++) { Row row = sheet.getRow(rIndex); if (row == null) { row = sheet.createRow(rIndex); } for (int cIndex = startCol; cIndex < startCol + colNum; cIndex++) { Cell cell = row.getCell(cIndex); if (cell == null) { cell = row.createCell(cIndex); } CellStyle style = cell.getCellStyle(); // 判斷是否已經建立過 if (style.getIndex() == 0) { style = workbook.createCellStyle(); } style.setFont(mFont); cell.setCellStyle(style); } } // 寫入文件,採用分批寫入的方式進行寫入 OutputStream outputStream = new FileOutputStream(m_FileName); SXSSFWorkbook sXSSFWorkbook = new SXSSFWorkbook(workbook, 1000); sXSSFWorkbook.write(outputStream); outputStream.close(); } catch (Exception e) { throw new Exception(String.format("setFont:%s", e.getMessage())); } } /** * 設置單元格的字體、大小、顏色(先執行Start方法) * * @param sheetIndex * Excel索引,從0開始 * @param startRow * 開始行,從0開始 * @param rowNum * 設置的行數 * @param startCol * 開始列,從0開始 * @param colNum * 設置的列數 * @param font * 字體:TimesRoman, Courier, Arial等 風格:三個常量 lFont.PLAIN, Font.BOLD, * Font.ITALIC 字號:字的大小(磅數) 字體名稱和大小 BOLDWEIGHT_NORMAL = 400; * BOLDWEIGHT_BOLD = 700 * @param color * 顏色 new Color(54, 201, 201) * @throws Exception */ public void setFont(int sheetIndex, int startRow, int rowNum, int startCol, int colNum, java.awt.Font font, java.awt.Color color) throws Exception { try { InputStream inputStream = new FileInputStream(m_FileName); XSSFWorkbook workbook = new XSSFWorkbook(inputStream); inputStream.close(); XSSFFont mFont = workbook.createFont(); mFont.setFontName(font.getFontName()); mFont.setFontHeightInPoints((short) font.getSize()); mFont.setColor(new XSSFColor(color)); if (font.isBold() == true) { mFont.setBoldweight((short) 700); } else { mFont.setBoldweight((short) 400); } Sheet sheet = workbook.getSheetAt(sheetIndex); // 設置單元格樣式 for (int rIndex = startRow; rIndex < startRow + rowNum; rIndex++) { Row row = sheet.getRow(rIndex); if (row == null) { row = sheet.createRow(rIndex); } for (int cIndex = startCol; cIndex < startCol + colNum; cIndex++) { Cell cell = row.getCell(cIndex); if (cell == null) { cell = row.createCell(cIndex); } CellStyle style = cell.getCellStyle(); // 判斷是否已經建立過 if (style.getIndex() == 0) { style = workbook.createCellStyle(); } style.setFont(mFont); cell.setCellStyle(style); } } // 寫入文件,採用分批寫入的方式進行寫入 OutputStream outputStream = new FileOutputStream(m_FileName); SXSSFWorkbook sXSSFWorkbook = new SXSSFWorkbook(workbook, 1000); sXSSFWorkbook.write(outputStream); outputStream.close(); } catch (Exception e) { throw new Exception(String.format("setFont2:%s", e.getMessage())); } } /** * 設置背景色(先執行Start方法) * * @param sheetIndex * Sheet的索引,從0開始 * @param startRow * 開始行,從0開始 * @param rowNum * 行數 * @param startCol * 開始列,從0開始 * @param colNum * 列數 * @param color * 顏色 new Color(54, 201, 201) * @throws Exception */ public void setBackgroundColor(int sheetIndex, int startRow, int rowNum, int startCol, int colNum, java.awt.Color color) throws Exception { try { InputStream inputStream = new FileInputStream(m_FileName); XSSFWorkbook workbook = new XSSFWorkbook(inputStream); inputStream.close(); Sheet sheet = workbook.getSheetAt(sheetIndex); // 設置單元格樣式 for (int rIndex = startRow; rIndex < startRow + rowNum; rIndex++) { Row row = sheet.getRow(rIndex); if (row == null) { row = sheet.createRow(rIndex); } for (int cIndex = startCol; cIndex < startCol + colNum; cIndex++) { Cell cell = row.getCell(cIndex); if (cell == null) { cell = row.createCell(cIndex); } XSSFCellStyle style = (XSSFCellStyle) cell.getCellStyle(); // 判斷是否已經建立過 if (style.getIndex() == 0) { style = workbook.createCellStyle(); } style.setFillForegroundColor(new XSSFColor(color)); style.setFillPattern(CellStyle.SOLID_FOREGROUND); cell.setCellStyle(style); } } // 寫入文件,採用分批寫入的方式進行寫入 OutputStream outputStream = new FileOutputStream(m_FileName); SXSSFWorkbook sXSSFWorkbook = new SXSSFWorkbook(workbook, 1000); sXSSFWorkbook.write(outputStream); outputStream.close(); } catch (Exception e) { throw new Exception(String.format("setBackgroudColor:%s", e .getMessage())); } } /** * 設置合併單元格(先執行Start方法) * * @param sheetIndex * Sheet的索引,從0開始 * @param firstRow * 開始行 * @param lastRow * 結束行 * @param firstCol * 開始列 * @param lastCol * 結束列 * @throws Exception */ public void setMerge(int sheetIndex, int firstRow, int lastRow, int firstCol, int lastCol) throws Exception { try { InputStream inputStream = new FileInputStream(m_FileName); XSSFWorkbook workbook = new XSSFWorkbook(inputStream); inputStream.close(); Sheet sheet = workbook.getSheetAt(sheetIndex); sheet.addMergedRegion(new CellRangeAddress(firstRow, lastRow, firstCol, lastCol)); // 寫入文件,採用分批寫入的方式進行寫入 OutputStream outputStream = new FileOutputStream(m_FileName); SXSSFWorkbook sXSSFWorkbook = new SXSSFWorkbook(workbook, 1000); sXSSFWorkbook.write(outputStream); outputStream.close(); } catch (Exception e) { throw new Exception(String.format("setMerge:%s", e.getMessage())); } } /** * 設置單元格的邊框(先執行Start方法) * * @param sheetIndex * Excel索引,從0開始 * @param startRow * 開始行,從0開始 * @param rowNum * 設置的行數 * @param startCol * 開始列,從0開始 * @param colNum * 須要設置的列數 * @throws Exception */ public void setBorder(int sheetIndex, int startRow, int rowNum, int startCol, int colNum) throws Exception { try { InputStream inputStream = new FileInputStream(m_FileName); XSSFWorkbook workbook = new XSSFWorkbook(inputStream); inputStream.close(); Sheet sheet = workbook.getSheetAt(sheetIndex); // 設置單元格樣式 for (int rIndex = startRow; rIndex < startRow + rowNum; rIndex++) { Row row = sheet.getRow(rIndex); if (row == null) { row = sheet.createRow(rIndex); } for (int cIndex = startCol; cIndex < startCol + colNum; cIndex++) { Cell cell = row.getCell(cIndex); if (cell == null) { cell = row.createCell(cIndex); } CellStyle style = cell.getCellStyle(); // 判斷是否已經建立過 if (style.getIndex() == 0) { style = workbook.createCellStyle(); } style.setBorderBottom(CellStyle.BORDER_THIN); style.setBorderLeft(CellStyle.BORDER_THIN); style.setBorderRight(CellStyle.BORDER_THIN); style.setBorderTop(CellStyle.BORDER_THIN); cell.setCellStyle(style); } } // 寫入文件,採用分批寫入的方式進行寫入 OutputStream outputStream = new FileOutputStream(m_FileName); SXSSFWorkbook sXSSFWorkbook = new SXSSFWorkbook(workbook, 1000); sXSSFWorkbook.write(outputStream); outputStream.close(); } catch (Exception e) { throw new Exception(String.format("setBorder:%s", e.getMessage())); } } /** * 設置行的高度(先執行Start方法) 說明:與Excel不是很對應,請多設置幾回高度值 * * @param sheetIndex * Excel索引,從0開始 * @param startRow * 開始行,從0開始 * @param rowNum * 行的數量 * @param height * 設置的高度 * @throws Exception */ public void setRowHeight(int sheetIndex, int startRow, int rowNum, short height) throws Exception { try { InputStream inputStream = new FileInputStream(m_FileName); XSSFWorkbook workbook = new XSSFWorkbook(inputStream); inputStream.close(); // 高度特殊處理 height = (short) (height * 20); Sheet sheet = workbook.getSheetAt(sheetIndex); for (int rIndex = startRow; rIndex < startRow + rowNum; rIndex++) { Row row = sheet.getRow(rIndex); if (row == null) { row = sheet.createRow(rIndex); } row.setHeight(height); } // 寫入文件,採用分批寫入的方式進行寫入 OutputStream outputStream = new FileOutputStream(m_FileName); SXSSFWorkbook sXSSFWorkbook = new SXSSFWorkbook(workbook, 1000); sXSSFWorkbook.write(outputStream); outputStream.close(); } catch (Exception e) { throw new Exception(String.format("setAutoFit:%s", e.getMessage())); } } /** * 設置列的寬度(先執行Start方法) 說明:與Excel不是很對應,請多設置幾回寬度值 * * @param sheetIndex * Excel索引,從0開始 * @param startCol * 開始列,從0開始 * @param colNum * 列數 * @param width * 寬度 * @throws Exception */ public void setColumnWidth(int sheetIndex, int startCol, int colNum, int width) throws Exception { try { InputStream inputStream = new FileInputStream(m_FileName); XSSFWorkbook workbook = new XSSFWorkbook(inputStream); inputStream.close(); // 寬度特殊處理 width = width * 275; Sheet sheet = workbook.getSheetAt(sheetIndex); for (int cIndex = startCol; cIndex < startCol + colNum; cIndex++) { sheet.setColumnWidth(cIndex, width); } // 寫入文件,採用分批寫入的方式進行寫入 OutputStream outputStream = new FileOutputStream(m_FileName); SXSSFWorkbook sXSSFWorkbook = new SXSSFWorkbook(workbook, 1000); sXSSFWorkbook.write(outputStream); outputStream.close(); } catch (Exception e) { throw new Exception(String.format("setAutoFit:%s", e.getMessage())); } } /** * 設置列自適應(先執行Start方法) * * @param sheetIndex * Sheet的索引,從0開始 * @param startCol * 開始列,從0開始 * @param colNum * 列數量 * @throws Exception */ public void setAutoFit(int sheetIndex, int startCol, int colNum) throws Exception { try { InputStream inputStream = new FileInputStream(m_FileName); XSSFWorkbook workbook = new XSSFWorkbook(inputStream); inputStream.close(); Sheet sheet = workbook.getSheetAt(sheetIndex); for (int cIndex = startCol; cIndex < startCol + colNum; cIndex++) { sheet.autoSizeColumn(cIndex); } // 寫入文件,採用分批寫入的方式進行寫入 OutputStream outputStream = new FileOutputStream(m_FileName); SXSSFWorkbook sXSSFWorkbook = new SXSSFWorkbook(workbook, 1000); sXSSFWorkbook.write(outputStream); outputStream.close(); } catch (Exception e) { throw new Exception(String.format("setAutoFit:%s", e.getMessage())); } } /** * 合併Excel * * @param toFileName * 寫入的文件路徑 * @param toSheetIndex * 寫入的文件SheetIndex,若是寫在最後請設置-1,不然請在Sheet數量範圍內 * @param fromFileName * 讀取的文件路徑 * @param fromSheetIndex * 讀取的文件SheetIndex * @throws Exception */ public void mergeExcel(String toFileName, int toSheetIndex, String fromFileName, int fromSheetIndex) throws Exception { try { // 一、打開Excel1 InputStream inputStream = new FileInputStream(toFileName); XSSFWorkbook toWorkbook = new XSSFWorkbook(inputStream); inputStream.close(); // 二、打開Excel2 inputStream = new FileInputStream(fromFileName); XSSFWorkbook fromWorkbook = new XSSFWorkbook(inputStream); inputStream.close(); // 三、複製Sheet,放在ToExcel1的Sheet上 copySheet(toWorkbook, toSheetIndex, fromWorkbook, fromSheetIndex); // 寫入Excel1文件 OutputStream outputStream = new FileOutputStream(toFileName); toWorkbook.write(outputStream); outputStream.close(); } catch (Exception e) { throw new Exception(String.format("mergeExcel:%s", e.getMessage())); } } private void copySheet(XSSFWorkbook toWorkbook, int toSheetIndex, XSSFWorkbook fromWorkbook, int fromSheetIndex) throws Exception { Sheet fromSheet = fromWorkbook.cloneSheet(fromSheetIndex); String sheetName = fromSheet.getSheetName().replace("(2)", ""); Sheet toSheet = toWorkbook.getSheet(sheetName); if (null == toSheet) { toSheet = toWorkbook.createSheet(sheetName); if(toSheetIndex >= 0){ toWorkbook.setSheetOrder(sheetName, toSheetIndex); } } else { throw new Exception("相同名稱的Sheet已存在"); } // 一、合併單元格 for (int mrIndex = 0; mrIndex < fromSheet.getNumMergedRegions(); mrIndex++) { CellRangeAddress cellRangeAddress = fromSheet .getMergedRegion(mrIndex); toSheet.addMergedRegion(cellRangeAddress); } // 二、單元格賦值,樣式等 Map<Integer, Integer> setColumnWidthIndex = new HashMap<Integer, Integer>(); Map<Short, Short> setFontIndex = new HashMap<Short, Short>(); for (int rIndex = fromSheet.getFirstRowNum(); rIndex <= fromSheet .getLastRowNum(); rIndex++) { Row fromRow = fromSheet.getRow(rIndex); if (null == fromRow) { continue; } Row toRow = toSheet.createRow(rIndex); // 設置行高,自動行高便可 //toRow.setHeight(fromRow.getHeight()); // 設置Cell的值和樣式 for (int cIndex = fromRow.getFirstCellNum(); cIndex <= fromRow .getLastCellNum(); cIndex++) { Cell fromCell = fromRow.getCell(cIndex); if (null == fromCell) { continue; } Cell toCell = toRow.createCell(cIndex); // 設置列寬 Integer isSet = setColumnWidthIndex.get(cIndex); if (null == isSet) { toSheet.setColumnWidth(cIndex, fromSheet .getColumnWidth(cIndex)); setColumnWidthIndex.put(cIndex, cIndex); } // 設置單元格樣式 CellStyle fromCellStyle = fromCell.getCellStyle(); if (fromCellStyle.getIndex() != 0) { XSSFCellStyle toCellStyle = toWorkbook.createCellStyle(); // 文字展現樣式 String fromDataFormat = fromCellStyle.getDataFormatString(); if ((null != fromDataFormat) && ("".equals(fromDataFormat) == false)) { DataFormat toDataFormat = toWorkbook.createDataFormat(); toCellStyle.setDataFormat(toDataFormat .getFormat(fromDataFormat)); } // 文字換行 toCellStyle.setWrapText(fromCellStyle.getWrapText()); // 文字對齊方式 toCellStyle.setAlignment(fromCellStyle.getAlignment()); toCellStyle.setVerticalAlignment(fromCellStyle .getVerticalAlignment()); // 單元格邊框 toCellStyle.setBorderLeft(fromCellStyle.getBorderLeft()); toCellStyle.setBorderRight(fromCellStyle.getBorderRight()); toCellStyle.setBorderTop(fromCellStyle.getBorderTop()); toCellStyle .setBorderBottom(fromCellStyle.getBorderBottom()); // 字體顏色,大小 short fromFontIndex = fromCellStyle.getFontIndex(); XSSFFont fromFont = fromWorkbook.getFontAt(fromFontIndex); Short toFontIndex = setFontIndex.get(fromFontIndex); if (null == toFontIndex) { XSSFFont toFont = toWorkbook.createFont(); toFont.setBoldweight(fromFont.getBoldweight()); toFont.setFontName(fromFont.getFontName()); toFont.setFontHeightInPoints(fromFont .getFontHeightInPoints()); toFont.setColor(fromFont.getXSSFColor()); toFont.setBold(fromFont.getBold()); toCellStyle.setFont(toFont); // 設置的Font加入集合中 toFontIndex = toFont.getIndex(); setFontIndex.put(fromFontIndex, toFontIndex); } else { XSSFFont toFont = toWorkbook.getFontAt(toFontIndex); toCellStyle.setFont(toFont); } // 背景色 XSSFColor fillForegroundColor = (XSSFColor) fromCellStyle .getFillForegroundColorColor(); toCellStyle.setFillForegroundColor(fillForegroundColor); toCellStyle.setFillPattern(fromCellStyle.getFillPattern()); toCell.setCellStyle(toCellStyle); } int fromCellType = fromCell.getCellType(); switch (fromCellType) { case Cell.CELL_TYPE_STRING: toCell.setCellValue(fromCell.getStringCellValue()); break; case Cell.CELL_TYPE_NUMERIC: toCell.setCellValue(fromCell.getNumericCellValue()); break; case Cell.CELL_TYPE_BOOLEAN: toCell.setCellValue(fromCell.getBooleanCellValue()); break; default: toCell.setCellValue(fromCell.getStringCellValue()); break; } } } } }
三、源碼下載緩存
SRCssh