创建 Workbook,取sheet内容
Workbook workbook = null;
File file = new File(filePath);
if (file.exists()) {
InputStream fis = new FileInputStream(file);//读取文件内容
workbook = WorkbookFactory.create(fis);
Sheet newsheet = null;
Sheet fromsheet = workbook.getSheetAt(0);//取第一个sheet内容
//复制第一个sheet内容到第二个,多个循环即可
copyRows(workbook, fromsheet, newsheet, fromsheet.getFirstRowNum(), fromsheet.getLastRowNum(), "动态修改单元格内容,不需要可去掉");
}
OutputStream out = response.getOutputStream();
workbook.write(out);
// 关闭流
out.close();
复制sheet内容没有限制.xls,.xlsx都可以
private static void copyRows(Workbook workbook, Sheet fromsheet, Sheet newsheet, int firstrow, int lastrow, String section) {
if ((firstrow == -1) || (lastrow == -1) || lastrow < firstrow) {
return;
}
// 拷贝合并的单元格
CellRangeAddress region = null;
for (int i = 0; i < fromsheet.getNumMergedRegions(); i++) {
region = fromsheet.getMergedRegion(i);
if ((region.getFirstRow() >= firstrow) && (region.getLastRow() <= lastrow)) {
newsheet.addMergedRegion(region);
}
}
Row fromRow = null;
Row newRow = null;
Cell newCell = null;
Cell fromCell = null;
// 设置列宽
for (int i = firstrow; i <= lastrow; i++) {
fromsheet.getRow(0).getCell(0);
fromRow = fromsheet.getRow(i);
if (fromRow != null) {
for (int j = fromRow.getLastCellNum(); j >= fromRow.getFirstCellNum(); j--) {
int colnum = fromsheet.getColumnWidth((short) j);
if (colnum > 100) {
newsheet.setColumnWidth((short) j, (short) colnum);
}
if (colnum == 0) {
newsheet.setColumnHidden((short) j, true);
} else {
newsheet.setColumnHidden((short) j, false);
}
}
break;
}
}
// 拷贝行并填充数据
for (int i = 0; i <= lastrow; i++) {
fromRow = fromsheet.getRow(i);
if (fromRow == null) {
continue;
}
newRow = newsheet.createRow(i - firstrow);
newRow.setHeight(fromRow.getHeight());
for (int j = fromRow.getFirstCellNum(); j < fromRow.getPhysicalNumberOfCells(); j++) {
fromCell = fromRow.getCell((short) j);
if (fromCell == null) {
continue;
}
newCell = newRow.createCell((short) j);
newCell.setCellStyle(fromCell.getCellStyle());
int cType = fromCell.getCellType();
newCell.setCellType(cType);
switch (cType) {
case HSSFCell.CELL_TYPE_STRING:
if (j == 0 && i == 0) {
newCell.setCellValue(section);//动态修改第一行第一列,不要可去掉判断
break;
} else {
newCell.setCellValue(fromCell.getRichStringCellValue());
break;
}
case HSSFCell.CELL_TYPE_NUMERIC:
newCell.setCellValue(fromCell.getNumericCellValue());
break;
case HSSFCell.CELL_TYPE_FORMULA:
newCell.setCellFormula(fromCell.getCellFormula());
break;
case HSSFCell.CELL_TYPE_BOOLEAN:
newCell.setCellValue(fromCell.getBooleanCellValue());
break;
case HSSFCell.CELL_TYPE_ERROR:
newCell.setCellValue(fromCell.getErrorCellValue());
break;
default:
newCell.setCellValue(fromCell.getRichStringCellValue());
break;
}
}
}
}