【问题标题】:Apache poi XLSX to XLSApache poi XLSX 到 XLS
【发布时间】:2021-07-07 14:44:37
【问题描述】:

我正在使用 apache poi,我读取了一些 xlsx 文件,对其进行处理,然后也以 xlsx 格式导出它们。但现在我要求导出格式为 XLS(这是为了支持旧设备)。有没有一种简单的方法可以将代码生成的 xlsx 文件转换为 xls?

所有的过程都是用 XSSF 实现的。

提前致谢。

【问题讨论】:

标签: java excel apache apache-poi


【解决方案1】:

我同意centic的回答,但我想补充几行代码。

你说你正在使用 XSSF 实现。

因此,对于您要保存的工作簿,请执行以下更改: 更改XSSFWorkbook x = new XSSFWorkbook();Workbook x = new HSSFWorkbook(); 其中 Workbook 是从 org.apache.poi.ss.usermodel.Workbook; 导入的

同样 从

更改 XSSFRow 实例化
XSSFRow r = newXSSF();

Row r = new HSSFRow(); 并从org.apache.poi.ss.usermodel.Row;导入行

同理,将 Cell 实例化改为 ss.usermodel 包。

最后用 .xls 扩展名保存您的 HSSF 工作簿。

【讨论】:

    【解决方案2】:

    您需要切换到允许透明地使用 HSSF (=XLS) 和 XSSF (=XSLX) 的“ss”实现,有关原始 HSSF -> SS 开关的一些详细信息,请参阅 http://poi.apache.org/spreadsheet/converting.html也为反过来支持它提供了一些启示。

    那么只需要 HSSFWorkbook/XSSFWorkbook 的两个构造函数来决定你要生成这两种格式中的哪一种。

    【讨论】:

      【解决方案3】:

      我遇到了同样的情况,并在下面使用 Java 将 XLSX 转换为 XLS 实现了代码

      以下代码将从目录中读取它并使用 apache camel(从路径轮询文件)和 apace poi 进行处理

      import java.io.BufferedOutputStream;
      import java.io.File;
      import java.io.FileOutputStream;
      import java.io.InputStream;
      import java.io.OutputStream;
      import java.util.Iterator;
      import java.util.Optional;
      
      import org.apache.camel.Exchange;
      import org.apache.camel.Processor;
      import org.apache.poi.hssf.usermodel.HSSFWorkbook;
      import org.apache.poi.ss.usermodel.Cell;
      import org.apache.poi.ss.usermodel.CellStyle;
      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.xssf.usermodel.XSSFWorkbook;
      import org.slf4j.Logger;
      import org.slf4j.LoggerFactory;
      import org.springframework.beans.factory.annotation.Value;
      import org.springframework.stereotype.Component;
      
      @Component
      public class ExcelFileProcessor implements Processor {
          final Logger logger = LoggerFactory.getLogger(getClass());
          
          @Value("${test.dir.in}")
          private String inDir;
          
          @Override
          public void process(Exchange exchange) throws Exception {
              logger.info("Entry-ExcelFileProcessor- Process method");
              long start = System.currentTimeMillis();
              
              String fileNameWithExtn=(String) exchange.getIn().getHeader("camelFileName");
              Long originalFileSize = (Long) exchange.getIn().getHeader("CamelFileLength");
              String fileNameWithOutExtn = fileNameWithOutExtn(fileNameWithExtn);
              
              logger.info("fileNameWithExtn:{}" ,fileNameWithExtn);
              logger.info("fileNameWithOutExtn:{}" ,fileNameWithOutExtn);
              logger.info("originalFileSize:{}" ,originalFileSize);
              
              try(InputStream in = exchange.getIn().getBody(InputStream.class);
                  XSSFWorkbook wbIn = new XSSFWorkbook(in);
                  Workbook wbOut = new HSSFWorkbook();) {
                  
                int sheetCnt = wbIn.getNumberOfSheets();
                for (int i = 0; i < sheetCnt; i++) {
                    Sheet sIn = wbIn.getSheetAt(0);
                    Sheet sOut = wbOut.createSheet(sIn.getSheetName());
                    Iterator<Row> rowIt = sIn.rowIterator();
                    while (rowIt.hasNext()) {
                        Row rowIn = rowIt.next();
                        Row rowOut = sOut.createRow(rowIn.getRowNum());
      
                        Iterator<Cell> cellIt = rowIn.cellIterator();
                        while (cellIt.hasNext()) {
                            Cell cellIn = cellIt.next();
                            Cell cellOut = rowOut.createCell(cellIn.getColumnIndex(), cellIn.getCellType());
      
                            switch (cellIn.getCellType()) {
                            case Cell.CELL_TYPE_BLANK: break;
      
                            case Cell.CELL_TYPE_BOOLEAN:
                                cellOut.setCellValue(cellIn.getBooleanCellValue());
                                break;
      
                            case Cell.CELL_TYPE_ERROR:
                                cellOut.setCellValue(cellIn.getErrorCellValue());
                                break;
      
                            case Cell.CELL_TYPE_FORMULA:
                                cellOut.setCellFormula(cellIn.getCellFormula());
                                break;
      
                            case Cell.CELL_TYPE_NUMERIC:
                                cellOut.setCellValue(cellIn.getNumericCellValue());
                                break;
      
                            case Cell.CELL_TYPE_STRING:
                                cellOut.setCellValue(cellIn.getStringCellValue());
                                break;
                            }
                            CellStyle styleIn = cellIn.getCellStyle();
                            CellStyle styleOut = cellOut.getCellStyle();
                            styleOut.setDataFormat(styleIn.getDataFormat());
                            cellOut.setCellComment(cellIn.getCellComment());
                           }
                    }
                }
                File outF = new File(inDir+fileNameWithOutExtn+".xls");
                try(OutputStream out = new BufferedOutputStream(new FileOutputStream(outF));){
                    wbOut.write(out);
                }
            }catch (Exception e) {
                  logger.info("Error during Excel file process:{}",e.getMessage());
            }
              long end = System.currentTimeMillis();
              logger.info("Total time processed for file in - {} ms", (end - start));
              logger.info("Exit-FileProcessor- Process method");
           }
          public String fileNameWithOutExtn(String fileName) {
              return Optional.of(fileName.lastIndexOf('.')).filter(i-> i >= 0)
                      .map(i-> fileName.substring(0, i)).orElse(fileName);
          }
      }
      

      如果你不使用camel并且想从sn-p下面的文件中获取输入流

          String inpFn = "input.xlsx"; 
          String outFn = "output.xls"; 
      
          InputStream in = new BufferedInputStream(new FileInputStream(inpFn));
          try {
              Workbook wbIn = new XSSFWorkbook(in);
              File outF = new File(outFn);
              if (outF.exists())
                  outF.delete();
      
              Workbook wbOut = new HSSFWorkbook();
              //continue with above code
      

      【讨论】:

        猜你喜欢
        • 2013-01-10
        • 1970-01-01
        • 2014-09-26
        • 2013-12-01
        • 1970-01-01
        • 2023-01-26
        • 1970-01-01
        • 1970-01-01
        • 2014-02-23
        相关资源
        最近更新 更多