java实现 xls转xlsx

提示:文章写完后,目录可以自动生成,如何生成可参考右边的帮助文档


前言


使用spark读取excel往数据库进行导数(现有插件spark-excel_2.12只支持读取xlsx),又因为数据源中存在大量xls类型的文件,需要开发一个功能将xls文件转为xlsx,来进行导数

一、使用步骤

1.引入依赖

代码如下(示例):

  <dependency>
            <groupId>org.apache.poi</groupId>
            <artifactId>poi</artifactId>
            <version>4.1.2</version>
        </dependency>
        <dependency>
            <groupId>org.apache.poi</groupId>
            <artifactId>poi-ooxml-schemas</artifactId>
            <version>4.1.2</version>
        </dependency>
        <dependency>
            <groupId>org.apache.poi</groupId>
            <artifactId>poi-ooxml</artifactId>
            <version>4.1.2</version>
        </dependency>

2.转换操作

代码如下(示例):

  /**
     * xls 文件转换为xlsx文件
     */

    public static String xls2xlsx(File sourceFile) throws IOException {

        //创建hssworkbook 操作xls 文件
        POIFSFileSystem fs = new POIFSFileSystem(new File(sourceFile.getPath()));
        HSSFWorkbook hssfWorkbook = new HSSFWorkbook(fs);

        //创建xssfworkbook 操作xlsx 文件
        XSSFWorkbook workbook = new XSSFWorkbook();
        int sheetNum = hssfWorkbook.getNumberOfSheets();

        String xlsxPath = createNewXlsxFilePath(sourceFile);

        for (int sheetIndex = 0; sheetIndex < sheetNum; sheetIndex++) {

            HSSFSheet hssfSheet = hssfWorkbook.getSheetAt(sheetIndex);

            if (workbook.getSheet(hssfSheet.getSheetName()) == null) {
                XSSFSheet xssfSheet = workbook.createSheet(hssfSheet.getSheetName());
                copySheets(hssfSheet, xssfSheet);
            } else {
                copySheets(hssfSheet, workbook.createSheet(hssfSheet.getSheetName()));
            }


            FileOutputStream fileOut = new FileOutputStream(xlsxPath);

            //将复制的xls数据写入到新的xlsx文件中
            workbook.write(fileOut);

            workbook.close();
            hssfWorkbook.close();

            //删除原有的xls文件  直接删除有点暴力 可以考虑在另外的目录下保存一下
            sourceFile.delete();
        }

        return  xlsxPath;
    }

//为xlsx创建路径
 public static String createNewXlsxFilePath(File sourceFile){

        String oldPath = sourceFile.getPath();
        String newPath = oldPath.substring(0,oldPath.indexOf("."))+".xlsx";

        return newPath;


    }


    /**
     * 转换为xlsx --创建sheet
     * @param source
     * @param destination
     */

    public static void copySheets(HSSFSheet source, XSSFSheet destination) {

        int maxColumnNum = 0;

        for (int i = source.getFirstRowNum(); i <= source.getLastRowNum(); i++) {
            HSSFRow srcRow = source.getRow(i);
            XSSFRow destRow = destination.createRow(i);
            if (srcRow != null) {
                // 拷贝行
                copyRow(srcRow, destRow);
                if (srcRow.getLastCellNum() > maxColumnNum) {
                    maxColumnNum = srcRow.getLastCellNum();
                }
            }
        }
        for (int i = 0; i <= maxColumnNum; i++) {
            destination.setColumnWidth(i, source.getColumnWidth(i));
        }

    }


    /**
     * 转换xlsx --  复制行
     * @param srcRow
     * @param destRow
     */
    public static void copyRow( HSSFRow srcRow, XSSFRow destRow) {

        // 拷贝行高
        destRow.setHeight(srcRow.getHeight());
        for (int j = srcRow.getFirstCellNum(); j <= srcRow.getLastCellNum(); j++) {
            HSSFCell oldCell = srcRow.getCell(j);
            XSSFCell newCell = destRow.getCell(j);
            if (oldCell != null) {
                if (newCell == null) {
                    newCell = destRow.createCell(j);
                }
                // 拷贝单元格
                copyCell(oldCell, newCell);

            }
        }

    }


    /**
     * 转换xlsx -- 复制单元格
     * @param oldCell
     * @param newCell
     */
    public static void copyCell(HSSFCell oldCell, XSSFCell newCell) {

        switch (oldCell.getCellType()) {
            case STRING:
                newCell.setCellValue(oldCell.getStringCellValue());
                break;
            case NUMERIC:
                newCell.setCellValue(oldCell.getNumericCellValue());
                break;
            case BLANK:
                newCell.setCellType(CellType.BLANK);
                break;
            case BOOLEAN:
                newCell.setCellValue(oldCell.getBooleanCellValue());
                break;
            case ERROR:
                newCell.setCellErrorValue(oldCell.getErrorCellValue());
                break;
            case FORMULA:
                newCell.setCellFormula(oldCell.getCellFormula());
                break;
            default:
                break;
        }

    }

注:如果需要考虑合并单元格,存在图片,复制表格样式等功能请参考
https://blog.csdn.net/sjyshine/article/details/121956034


  • 1
    点赞
  • 6
    收藏
    觉得还不错? 一键收藏
  • 1
    评论
Java可以通过使用Apache POI库来实现xls文件换为xlsx文件。 首先,我们需要在Java项目中引入Apache POI的相关依赖项。在maven项目中,可以在pom.xml文件中添加以下依赖项: ``` <dependency> <groupId>org.apache.poi</groupId> <artifactId>poi</artifactId> <version>4.1.2</version> </dependency> <dependency> <groupId>org.apache.poi</groupId> <artifactId>poi-ooxml</artifactId> <version>4.1.2</version> </dependency> ``` 接下来,我们可以使用以下代码来实现xls文件换为xlsx文件: ```java import org.apache.poi.ss.usermodel.*; import org.apache.poi.xssf.usermodel.XSSFWorkbook; import org.apache.poi.hssf.usermodel.HSSFWorkbook; import java.io.FileInputStream; import java.io.FileOutputStream; import java.io.IOException; public class ExcelConverter { public static void main(String[] args) { String inputFile = "input.xls"; // 输入的xls文件路径 String outputFile = "output.xlsx"; // 输出的xlsx文件路径 try { FileInputStream inputStream = new FileInputStream(inputFile); Workbook inputWorkbook = new HSSFWorkbook(inputStream); // 创建xls工作簿 Workbook outputWorkbook = new XSSFWorkbook(); // 创建xlsx工作簿 int numberOfSheets = inputWorkbook.getNumberOfSheets(); // 获取xls中的工作表数量 for (int i = 0; i < numberOfSheets; i++) { Sheet inputSheet = inputWorkbook.getSheetAt(i); // 获取xls中的一个工作表 Sheet outputSheet = outputWorkbook.createSheet(inputSheet.getSheetName()); // 创建对应的工作表到xlsx文件中 int rowCount = inputSheet.getLastRowNum(); for (int j = 0; j <= rowCount; j++) { Row inputRow = inputSheet.getRow(j); // 获取xls中的一行数据 Row outputRow = outputSheet.createRow(j); // 创建对应的行到xlsx文件中 int cellCount = inputRow.getLastCellNum(); for (int k = 0; k < cellCount; k++) { Cell inputCell = inputRow.getCell(k); // 获取xls中的一个单元格 Cell outputCell = outputRow.createCell(k); // 创建对应的单元格到xlsx文件中 outputCell.setCellValue(inputCell.getStringCellValue()); // 将xls单元格的值复制到xlsx单元格 } } } FileOutputStream outputStream = new FileOutputStream(outputFile); outputWorkbook.write(outputStream); // 将xlsx工作簿保存到文件中 outputStream.close(); inputWorkbook.close(); outputWorkbook.close(); System.out.println("换成功!"); } catch (IOException e) { e.printStackTrace(); } } } ``` 以上代码将读取名为"input.xls"的xls文件,将其内容复制到一个新创建的名为"output.xlsx"的xlsx文件中。换完成后,控制台将输出"换成功!"。 这就是使用Javaxls文件换为xlsx文件的基本步骤。你可以根据需要进行进一步的定制和优化。

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

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

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值