用poi把xls格式转换成xlsx格式

这篇具有很好参考价值的文章主要介绍了用poi把xls格式转换成xlsx格式。希望对大家有所帮助。如果存在错误或未考虑完全的地方,请大家不吝赐教,您也可以点击"举报违法"按钮提交疑问。

java中要实现excel新老格式的转换比较麻烦,开源库也没几个好用的。用ChatGpt查询也是推荐直接用POI,下面是借助ChatGPT写出来的代码,经过小小修改,格式转换良好,基本能用,就是效率比较低下。将就着用吧,哎!
package com.yc.cloud.excel.util;

import lombok.extern.slf4j.Slf4j;
import org.apache.poi.hssf.usermodel.*;
import org.apache.poi.ss.usermodel.DateUtil;
import org.apache.poi.ss.util.CellRangeAddress;
import org.apache.poi.xssf.usermodel.*;

import java.io.InputStream;
import java.io.OutputStream;
import java.util.List;

@Slf4j
public class ExcelFmtConvert {

    /**
     * Excel格式从xls转换成xlsx格式
     *
     * @param xlsInputStream   xls格式的输入流
     * @param xlsxOutputStream xlsx格式的输出流
     */
    public static void convertXlsToXlsxByStream(InputStream xlsInputStream, OutputStream xlsxOutputStream) {
        try {
            HSSFWorkbook oldWorkbook = new HSSFWorkbook(xlsInputStream);
            XSSFWorkbook newWorkbook = new XSSFWorkbook();

            for (int i = 0; i < oldWorkbook.getNumberOfSheets(); i++) {
                HSSFSheet oldSheet = oldWorkbook.getSheetAt(i);
                XSSFSheet newSheet = newWorkbook.createSheet(oldSheet.getSheetName());

                // 遍历行,创建行
                for (int j = 0; j <= oldSheet.getLastRowNum(); j++) {
                    HSSFRow oldRow = oldSheet.getRow(j);
                    XSSFRow newRow = newSheet.createRow(j);
                    if (oldRow != null) {
                        // 复制行高
                        newRow.setHeight(oldRow.getHeight());

                        //遍历列,复制单元格
                        for (int k = 0; k < oldRow.getLastCellNum(); k++) {
                            HSSFCell oldCell = oldRow.getCell(k);
                            XSSFCell newCell = newRow.createCell(k);
                            if (oldCell != null) {
                                try {
                                    setCellValue(newCell, oldCell);
                                    copyCellStyle(newWorkbook, newCell, oldWorkbook, oldCell);
                                } catch (Exception ex) {
                                    log.warn("单元格拷贝异常:", ex);
                                }
                            }
                        }
                    }
                }

                // 复制单元格合并信息
                List<CellRangeAddress> mergedRegions = oldSheet.getMergedRegions();
                for (CellRangeAddress mergedRegion : mergedRegions) {
                    CellRangeAddress targetMergedRegion = new CellRangeAddress(
                            mergedRegion.getFirstRow(),
                            mergedRegion.getLastRow(),
                            mergedRegion.getFirstColumn(),
                            mergedRegion.getLastColumn()
                    );
                    newSheet.addMergedRegion(targetMergedRegion);
                }

                // 复制列宽
                int columnCount = 0;
                if (newSheet.getRow(0) != null) {
                    // 假设第一行包含所有列,根据第一行的列数获取列数
                    columnCount = newSheet.getRow(0).getLastCellNum();
                }
                for (int columnIndex = 0; columnIndex < columnCount; columnIndex++) {
                    newSheet.setColumnWidth(columnIndex, oldSheet.getColumnWidth(columnIndex));
                }
            }

            newWorkbook.write(xlsxOutputStream);
            oldWorkbook.close();
            newWorkbook.close();
        } catch (Exception e) {
            log.error("excel格式转换(xls->xlsx)异常:", e);
        }
    }

    private static void setCellValue(XSSFCell newCell, HSSFCell oldCell) {
        if (oldCell == null) {
            return;
        }
        switch (oldCell.getCellType()) {
            case STRING:
                newCell.setCellValue(oldCell.getStringCellValue());
                break;
            case NUMERIC:
                if (DateUtil.isCellDateFormatted(oldCell)) {
                    newCell.setCellValue(oldCell.getDateCellValue());
                } else {
                    newCell.setCellValue(oldCell.getNumericCellValue());
                }
                break;
            case BOOLEAN:
                newCell.setCellValue(oldCell.getBooleanCellValue());
                break;
            case FORMULA:
                newCell.setCellValue(oldCell.getCellFormula());
                break;
            default:
        }
    }

    private static void copyCellStyle(XSSFWorkbook xssfWorkbook, XSSFCell newCell, HSSFWorkbook hssfWorkbook, HSSFCell oldCell) {
        HSSFCellStyle oldCellStyle = oldCell.getCellStyle();

        // 创建一个XSSFCellStyle(新Excel格式)
        XSSFCellStyle newCellStyle = xssfWorkbook.createCellStyle();

        // 复制对齐方式
        newCellStyle.setAlignment(oldCellStyle.getAlignment());
        newCellStyle.setVerticalAlignment(oldCellStyle.getVerticalAlignment());

        // 复制字体属性
        XSSFFont newFont = xssfWorkbook.createFont();
        HSSFFont oldFont = oldCellStyle.getFont(hssfWorkbook);
        newFont.setFontName(oldFont.getFontName());
        newFont.setFontHeightInPoints(oldFont.getFontHeightInPoints());
        newFont.setColor(oldFont.getColor());
        newCellStyle.setFont(newFont);

        // 复制填充颜色
        newCellStyle.setFillPattern(oldCellStyle.getFillPattern());
        newCellStyle.setFillForegroundColor(oldCellStyle.getFillForegroundColor());
        newCellStyle.setFillBackgroundColor(oldCellStyle.getFillBackgroundColor());

        // 复制数据格式
        newCellStyle.setDataFormat(oldCellStyle.getDataFormat());

        newCell.setCellStyle(newCellStyle);
    }
}

 文章来源地址https://www.toymoban.com/news/detail-688073.html

 

到了这里,关于用poi把xls格式转换成xlsx格式的文章就介绍完了。如果您还想了解更多内容,请在右上角搜索TOY模板网以前的文章或继续浏览下面的相关文章,希望大家以后多多支持TOY模板网!

本文来自互联网用户投稿,该文观点仅代表作者本人,不代表本站立场。本站仅提供信息存储空间服务,不拥有所有权,不承担相关法律责任。如若转载,请注明出处: 如若内容造成侵权/违法违规/事实不符,请点击违法举报进行投诉反馈,一经查实,立即删除!

领支付宝红包 赞助服务器费用

相关文章

  • 文件格式xls和xlsx有什么区别?xlsx和xls选择哪个

    在数字时代,我们经常需要处理各种电子文件,其中xls和xlsx是两种常见的电子表格文件格式。尽管它们只有一字之差,但它们在功能、兼容性和性能等方面有着显著的区别。本文将详细解析这两种文件格式的区别,并指导您如何根据需求选择合适的格式。 XLS是Microsoft Excel的

    2024年01月24日
    浏览(43)
  • 后缀xls和xlsx有什么区别,xls和xlsx怎么转换

    两种后缀名 都是office excel的生成文件; 其中xls是早期的office生成的文件;office2010之前的版本; xlsx是office2010之后的版本excel生成的文件; office 安装包 含新版本 如果你想相互转化,那就通过另存为,保存对应的后缀名即可; 新建的Excel保存时,需要指定保存类型。目前主流

    2024年02月07日
    浏览(31)
  • Java excel poi 使用HSSFWorkbook 导出的excel wps能打开office打不开问题解决 Excel无法打开xx.xlsx,因为文件格式或扩展名无效......

    1.在开发代码中涉及到报表导出 xlsx文件 office打不开问题 JavaPOI导出Excel有三种形式,他们分别是 1.HSSFWorkbook 2.XSSFWorkbook 3.SXSSFWorkbook。 pom文件如下 检查创建sheet代码如下 代码中用了 HSSFworkbook 去创建Sheet 导致office打不开原因就在这里 HSSFworkbook 解释如下: HSSFWorkbook:是操作Exc

    2024年02月16日
    浏览(30)
  • 【Unity】用Excel库读取Excel表格(.xlsx或者.xls)

    首先需要下载解析的库  EPPlus,  Excel,  ICSharpCode.SharpZipLib    下载链接: https://download.csdn.net/download/weixin_46472622/87238048 使用方法 我的Excel 表格是这样的,每一列有一个 我用一个结构体对象来表示 读取的方法  全部代码,以及调用: 如果是打包PC端的exe,需要将编辑

    2024年02月12日
    浏览(33)
  • python 将 csv转excel (.xls和.xlsx)的几种方式

    excel 后缀有2种格式, .xls 是从 Excel 97 到 Excel 2003 的默认文件格式,而 .xlsx 是 Excel 2007 及更高版本的默认文件格式。 .xlsx和.xls格式的主要区别在于,.xls格式单个工作表最多支持65536行,256列。 .xlsx格式最多支持1048576行,16384列。 此外就是,存储同样多的数据,.xlsx格式文件更

    2024年02月08日
    浏览(68)
  • vue - - - - - 在线预览常见文件格式 .doc, .docx, .xls, .xlsx,.pdf

    关于一些文件的在线预览,最简易的实现方式是什么呢? 写在前面 .png, .jpg, .jpeg 等图片格式 直接预览http/https地址 即可 .pdf 文件 直接预览http/https地址 即可 .doc, .docx, .xls, .xlsx 等类型文件,需要在预览地址之前拼接上 https://view.officeapps.live.com/op/view.aspx?src= .ofd 等类型文件,需

    2024年02月09日
    浏览(55)
  • 用python将csv转excel (.xls和.xlsx)的几种方式

    excel 后缀有2种格式, .xls 是从 Excel 97 到 Excel 2003 的默认文件格式,而 .xlsx 是 Excel 2007 及更高版本的默认文件格式。 .xlsx和.xls格式的主要区别在于,.xls格式单个工作表最多支持65536行,256列。 .xlsx格式最多支持1048576行,16384列。 此外就是,存储同样多的数据,.xlsx格式文件更

    2024年02月05日
    浏览(44)
  • VBA:Application.GetOpenFilename打开指定文件夹里的excel类型文件(xls、xlsx)

    \\\'GetOpenFilename相当于Excel打开窗口,通过该窗口选择要打开的文件,并可以返回选择的文件完整路径和文件名。 \\\'Application.GetOpenFilename(“文件类型筛选规则(就是说明)”,“优先显示第几个类型的文件”,“标题”,“是否允许选择多个文件名”) 打开类型只限excel文件 \\\'“文件类型

    2024年02月11日
    浏览(34)
  • Node.js 使用 officecrypto-tool 读取加密的 Excel (xls, xlsx) 和 Word( docx)文档

    Node.js 使用 officecrypto-tool 读取加密的 Excel (xls, xlsx) 和 Word( docx)文档, 还支持 xlsx 和 docx 文件的加密(具体使用看文档)。暂时不支持doc文件的解密 传送门:officecrypto-tool 读取加密的 Excel 示例 读取加密的 Word 示例 使用:mammoth officecrypto-tool 使用其他的word读取库也是一样的道理

    2024年02月10日
    浏览(33)

觉得文章有用就打赏一下文章作者

支付宝扫一扫打赏

博客赞助

微信扫一扫打赏

请作者喝杯咖啡吧~博客赞助

支付宝扫一扫领取红包,优惠每天领

二维码1

领取红包

二维码2

领红包