当前位置:   article > 正文

java poi 通过excel模板导出并且生成多个sheet_hssfworkbook 多模板 多sheet

hssfworkbook 多模板 多sheet
根据EXCEL模板导出EXCEL,已经在上一遍博客里写到了《 关于JAVA 用POI 通过EXCEL模板 导出Excel 》;
下面写一下,关于通过excel模板生成之后,生成多个sheet;
代码如下: (只写关键代码)
FileOutputStream fileOut = new FileOutputStream("D:\\excel.xls");
HSSFWorkbook workbook = null;
InputStream fis = new FileInputStream(filePath);
workbook = new HSSFWorkbook(fis);
for (int i = 0; i < 3; i++) {
HSSFSheet newsheet = null;
HSSFSheet fromsheet = workbook.getSheet("sheet1");
newsheet = workbook
.createSheet("tt_" + (String.valueOf(i + 1)));
copyRows(workbook, fromsheet, newsheet, fromsheet
.getFirstRowNum(), fromsheet.getLastRowNum());
}

@SuppressWarnings("deprecation")
private static void copyRows(HSSFWorkbook workbook, HSSFSheet fromsheet, HSSFSheet newsheet, int firstrow, int lastrow)
{
if ((firstrow == -1) || (lastrow == -1) || lastrow < firstrow)
{
return;
}
// 拷贝合并的单元格
Region region = null;
for (int i = 0; i < fromsheet.getNumMergedRegions(); i++)
{
region = fromsheet.getMergedRegionAt(i);
if ((region.getRowFrom() >= firstrow) && (region.getRowTo() <= lastrow))
{
newsheet.addMergedRegion(region);
}
}
HSSFRow fromRow = null;
HSSFRow newRow = null;
HSSFCell newCell = null;
HSSFCell fromCell = null;
// 设置列宽
for (int i = firstrow; i <= lastrow; i++)
{
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:
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;
}
}
}

}
声明:本文内容由网友自发贡献,不代表【wpsshop博客】立场,版权归原作者所有,本站不承担相应法律责任。如您发现有侵权的内容,请联系我们。转载请注明出处:https://www.wpsshop.cn/w/我家自动化/article/detail/272951
推荐阅读
相关标签
  

闽ICP备14008679号