POI根据Excel模板导出数据

    Excel和Word数据导入导出通用程序今天已经完成了。把excel的部分代码贴过来吧。
     public  File export(Class dtoClass, Object[] dtos,  int  recordCountPerSheet) {
    
    Assert.notNull(dtoClass);
    Assert.isTrue(dtos 
instanceof  Dto[]);
    
    POIFSFileSystem fis 
=   null ;
    
try  {
        
// 获得excel模板
        fis  =   new  POIFSFileSystem(loadExcleTemplate(dtoClass)); 
    } 
catch (IOException e) {
        
if (logger.isErrorEnabled()) {
        logger.error(e);
        }
        
throw   new  ExportException(e);
    }
    
    OutputStream fileOut 
=   null ;
    File excelOutput 
=   null ;
    
try  {
        HSSFWorkbook wb 
=   new  HSSFWorkbook(fis);
        excelOutput 
=   this .generateFile();
        fileOut 
=   
        
new  BufferedOutputStream( new  FileOutputStream(excelOutput), Constants.DEFAULT_BUFFER_SIZE);
        
        
if (dtos  !=   null ) {
        ExportDto exportDto 
=  (ExportDto) mappingCache.get(dtoClass.getName());
        
int  dtoLength  =  dtos.length;
        
// 根据总的记录条数和每个sheet输出的条数计算出sheet个数
         int  sheetCount  =  caculateSheetCount(dtoLength, recordCountPerSheet);
        
// 获得第一页的模板
        HSSFSheet templateSheet  =  wb.getSheetAt( 0 );
        
int  dtoIndexStart  =   0 ;
        
int  dtoIndexEnd  =  caculateDtoIndexEnd(dtoIndexStart, recordCountPerSheet, dtoLength);
        
for ( int  sheetIndex  =   0 ; sheetIndex  <  sheetCount; sheetIndex  ++ ) {
            
// 根据模板的sheet复制一个新的sheet
            HSSFSheet newSheet  =  createHSSFSheet(sheetIndex, wb, templateSheet, exportDto);
            
// 对新建的sheet填充数据
             for ( int  dtoIndex  =  dtoIndexStart; dtoIndex  <  dtoIndexEnd; dtoIndex  ++ ) {
            processRow(exportDto.getStartRow() 
-   1   +  dtoIndex  %  recordCountPerSheet, exportDto, (Dto)dtos[dtoIndex], newSheet);
            }
            dtoIndexStart 
=  dtoIndexEnd;
            dtoIndexEnd 
=  caculateDtoIndexEnd(dtoIndexStart, recordCountPerSheet, dtoLength);
        }
        }
        wb.removeSheetAt(
0 ); // 删除拷贝模板的第一页
        wb.write(fileOut);
        fileOut.flush();
        
return  excelOutput;
    } 
catch (Throwable e) {
        
if (logger.isErrorEnabled()) {
        logger.error(e);
        }
        
        
if (excelOutput  !=   null   &&  excelOutput.exists()) {
            excelOutput.delete();
        }
        
throw   new  ExportException(e);
    } 
finally  {
        
if (fileOut  !=   null ) {
        
try  {
            fileOut.close();
        } 
catch (IOException e) {
            
if (logger.isErrorEnabled()) {
            logger.error(e);
            }
        }
        }
    }
    }
 
     private  InputStream loadExcleTemplate(Class dtoClass)  throws  IOException {
    Assert.notNull(templateCache);
    Resource template 
=  (Resource) templateCache.get(dtoClass.getName());
    
return  template.getInputStream();
    }

    
private  HSSFSheet createHSSFSheet( int  sheetIndex, HSSFWorkbook wb, HSSFSheet templateSheet, ExportDto exportDto) {
    
    HSSFSheet newSheet 
=  wb.createSheet();
    
    
int  startRow  =  exportDto.getStartRow();
    
int  columnCount  =  exportDto.getExportDtoFieldsCount()  +  exportDto.getStartColumn()  -   1 ;
    
    
// 拷贝设置的开始行的上面所有行
     for ( int  i  =   0 ; i  <  startRow; i  ++ ) {
        HSSFRow templateRow 
=  templateSheet.getRow(i);
        
if (templateRow  !=   null ) {
            HSSFRow newRow 
=  newSheet.createRow(i);
            
for ( int  j  =   0 ; j  <  columnCount; j  ++ ) {
            HSSFCell templateCell 
=  templateRow.getCell(( short )j);
            
if (templateCell  !=   null ) {
                HSSFCell newCell 
=  newRow.createCell(( short )j);
                copyCell(templateCell, newCell);                
            }
            }
        }
    }
    
return  newSheet;
    }

    
private   void  copyCell(HSSFCell srcCell, HSSFCell distCell) {
    distCell.setCellStyle(srcCell.getCellStyle());
    
if (srcCell.getCellComment()  !=   null ) {
        distCell.setCellComment(srcCell.getCellComment());        
    }
    
int  srcCellType  =  srcCell.getCellType();
    distCell.setCellType(srcCellType);
    
if  (srcCellType  ==  HSSFCell.CELL_TYPE_NUMERIC) {
        
if  (HSSFDateUtil.isCellDateFormatted(srcCell)) {
        distCell.setCellValue(srcCell.getDateCellValue());
        } 
else  {
        distCell.setCellValue(srcCell.getNumericCellValue());
        }
    } 
else   if  (srcCellType  ==  HSSFCell.CELL_TYPE_STRING) {
        distCell.setCellValue(srcCell.getRichStringCellValue());
    } 
else   if  (srcCellType  ==  HSSFCell.CELL_TYPE_BLANK) {

    } 
else   if  (srcCellType  ==  HSSFCell.CELL_TYPE_BOOLEAN) {
        distCell.setCellValue(srcCell.getBooleanCellValue());
    } 
else   if  (srcCellType  ==  HSSFCell.CELL_TYPE_ERROR) {
        distCell.setCellErrorValue(srcCell.getErrorCellValue());
    } 
else   if  (srcCellType  ==  HSSFCell.CELL_TYPE_FORMULA) {
        distCell.setCellFormula(srcCell.getCellFormula());
    } 
else  {
    }
    }
  • 0
    点赞
  • 9
    收藏
    觉得还不错? 一键收藏
  • 13
    评论
您好!您可以使用Java的POI库来根据现有的模板导出Excel文件。下面是一个简单的示例代码,演示了如何使用POI来实现这个需求: ```java import org.apache.poi.ss.usermodel.*; import org.apache.poi.xssf.usermodel.XSSFWorkbook; import java.io.*; public class ExcelExportExample { public static void main(String[] args) { String templatePath = "path/to/template.xlsx"; String outputPath = "path/to/output.xlsx"; try { FileInputStream fis = new FileInputStream(templatePath); Workbook workbook = new XSSFWorkbook(fis); Sheet sheet = workbook.getSheetAt(0); // 在模板中找到需要填充数据的位置,假设要填充的单元格是A1 Row row = sheet.getRow(0); Cell cell = row.getCell(0); // 填充数据到单元格中 cell.setCellValue("Hello, World!"); // 将修改后的Excel文件写入输出流 FileOutputStream fos = new FileOutputStream(outputPath); workbook.write(fos); // 关闭资源 fos.close(); workbook.close(); System.out.println("Excel导出成功!"); } catch (IOException e) { e.printStackTrace(); } } } ``` 在上述代码中,您需要将`templatePath`替换为实际的模板文件路径,`outputPath`替换为导出Excel文件保存路径。然后,您可以通过`Workbook`对象获取要填充数据的单元格,并使用`setCellValue`方法将数据填充到单元格中。最后,通过`FileOutputStream`将修改后的Excel写入到输出流中。 希望这个示例对您有帮助!如果您有任何其他问题,请随时提问。

“相关推荐”对你有帮助么?

  • 非常没帮助
  • 没帮助
  • 一般
  • 有帮助
  • 非常有帮助
提交
评论 13
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值