聲明:文章內容全都是自己的學習總結,如有不對的地方請大家幫忙指出。有需要溝通交流的可加我QQ羣:425120333
原先用jxl中的合併多個Sheel表工具類,總是報空指針異常,網上找了資料,解決辦法是改工具包中的源碼。看看挺麻煩的,就直接去寫了一個合併的工具方法。
private final static Log logger = LogFactory.getLog(ExcelUtil.class);
/**
* @introduction: 將多個Excel文件中的sheel合併到一個Excel中(例:Excel1有2個sheel,Excel2有3個sheel,合併後的會有5個)
* @param outputFileName
* @param inputFileNameArray
*/
public static void mergeExcel(String outputFileName, String... inputFileNameArray) {
if (inputFileNameArray.length == 1) {
logger.info("至少需要兩個文件才能合併,請驗證!!!");
return;
}
try {
WritableWorkbook outputExcel = Workbook.createWorkbook(new File(outputFileName));
int index = 0;
for (String fileName : inputFileNameArray) {
Workbook inputExcel = Workbook.getWorkbook(new FileInputStream(fileName));
Sheet[] sheets = inputExcel.getSheets();
for (Sheet sheet : sheets) {
WritableSheet writableSheet = outputExcel.createSheet(sheet.getName(), index);
copy(sheet, writableSheet);
index++;
}
}
/** **********將以上緩存中的內容寫到EXCEL文件中******** */
outputExcel.write();
/** *********關閉文件************* */
outputExcel.close();
} catch (Exception e) {
StringWriter sw = new StringWriter();
PrintWriter pw = new PrintWriter(sw);
e.printStackTrace(pw);
logger.error(sw.toString());
}
}
private static void copy(Sheet formSheet, WritableSheet toWritableSheet) {
int rows = formSheet.getRows();
int columns = formSheet.getColumns();
for (int rowIndex = 0; rowIndex < rows; rowIndex++) {
for (int columnIndex = 0; columnIndex < columns; columnIndex++) {
Cell cell = formSheet.getCell(columnIndex, rowIndex);
try {
CellFormat wcf = new WritableCellFormat();
if (cell.getCellFormat() != null) {
wcf = cell.getCellFormat();
}
toWritableSheet.addCell(new Label(columnIndex, rowIndex, cell.getContents(), wcf));
} catch (Exception e) {
StringWriter sw = new StringWriter();
PrintWriter pw = new PrintWriter(sw);
e.printStackTrace(pw);
logger.error(sw.toString());
}
}
}
}
僅供參考,可以根據自己的需求加以變動。