使用 Apache POI 将结果集转换为 Excel (*.xlsx) 表

2024-05-07

我正在尝试写结果集到 Excel (*.xlsx) 表使用 Apache Poi。

Office Excel 中的无效表对象错误

但是,即使它写入 Excel 文件时没有任何错误,但当我尝试在 Office Excel 2013 中打开它时,它会显示错误并删除表对象以仅提供纯数据视图。

这是粗略的示例代码使用这个例子 http://svn.apache.org/repos/asf/poi/trunk/src/examples/src/org/apache/poi/xssf/usermodel/examples/CreateTable.java:

public static void writeExcel(ResultSet rs, int sqliteRowCount, String dir) {
    System.out.println("Writing Excel(*.xlsx) File...");
    XSSFWorkbook workbook = null;
    try {
        if (rs != null) {
            // Get ResultSet MetaData
            ResultSetMetaData rsmd = rs.getMetaData();
            // Number of columns
            int numColumns = rsmd.getColumnCount();
            // Number of rows
            // + 1 for headers
            int numRows = sqliteRowCount + 1;
            workbook = new XSSFWorkbook();

            // Create Excel Table
            XSSFSheet sheet = workbook.createSheet("Text");
            XSSFTable table = sheet.createTable();
            table.setDisplayName("Test");
            CTTable cttable;
            cttable = table.getCTTable();

            // Style configurations
            CTTableStyleInfo style = cttable.addNewTableStyleInfo();
            style.setName("TableStyleMedium16");
            style.setShowColumnStripes(false);
            style.setShowRowStripes(true);

            // Set Table Span Area
            AreaReference reference = new AreaReference(new CellReference(0, 0), new CellReference(numRows - 1, numColumns - 1));
            cttable.setRef(reference.formatAsString());
            cttable.setId(1);
            cttable.setName("Test");
            cttable.setDisplayName("Test");
            cttable.setTotalsRowCount(numRows);
            cttable.setTotalsRowShown(false);

            // Create Columns
            CTTableColumns columns = cttable.addNewTableColumns();
            columns.setCount(numColumns);

            // Create Column, Row, Cell Objects
            CTTableColumn column;
            XSSFRow row;

            // Add Header and Columns
            XSSFRow headerRow = sheet.createRow(0);
            for (int i = 0; i < numColumns; i++) {
                column = columns.addNewTableColumn();
                column.setName("Column" + (i + 1));
                column.setId(i + 1);
                headerRow.createCell(i).setCellValue(rsmd.getColumnLabel(i + 1));
            }

            // Write each row from ResultSet
            int rowNumber = 1;
            while (rs.next()) {
                row = sheet.createRow(rowNumber);
                for (int y = 0; y < numColumns; y++) {
                    row.createCell(y).setCellValue(rs.getString(y + 1));
                }
                rowNumber++;
            }

            // Set AutoFilter
            CTAutoFilter fltr = CTAutoFilter.Factory.newInstance();
            fltr.setRef((new AreaReference(new CellReference(0, 0), new CellReference(numRows - 1, numColumns - 1))).formatAsString());
            cttable.setAutoFilter(fltr);
            // sheet.setAutoFilter(CellRangeAddress.valueOf((new AreaReference(new CellReference(0, 0), new CellReference(numRows - 1, numColumns - 1))).formatAsString()));
            // Freeze Pan
            sheet.createFreezePane(0, 1, 0, 2);
        }
    } catch (SQLException ex) {
        System.out.println("SQL Error while writing Excel file!");
    } finally {
        try {
        // Let's write the excel file now
            if (workbook != null) {
                String excelDir = dir + File.separator + "workbook.xlsx";
                try (final FileOutputStream out = new FileOutputStream(excelDir)) {
                    workbook.write(out);
                }
            }
        } catch (IOException ex) {
            System.out.println("IO Error while writing Excel summary file!");
        }
    }
}

我知道我的代码有问题,但无法弄清楚。 任何想法,为什么会发生这种情况,我的代码中可能存在潜在错误。

更新1:

Excel 存档中的表 XML 文件(如果使用 Apache POI 创建)

<?xml version="1.0" encoding="UTF-8"?>
<table displayName="Test" ref="A1:B881" id="1" name="Test" totalsRowCount="881" xmlns="http://schemas.openxmlformats.org/spreadsheetml/2006/main" totalsRowShown="0"><autoFilter ref="A1:B881"/><tableColumns count="2"><tableColumn name="ID" id="1"/><tableColumn name="Name" id="2"/><tableStyleInfo name="TableStyleMedium2" showColumnStripes="true" showRowStripes="true"/></table>

如果手动创建表,则 Excel 存档中的表 XML 文件

<?xml version="1.0" encoding="UTF-8" standalone="yes"?>
<table xmlns="http://schemas.openxmlformats.org/spreadsheetml/2006/main" id="1" name="Table1" displayName="Table1" ref="A1:B881" totalsRowShown="0"><autoFilter ref="A1:B881"/><tableColumns count="2"><tableColumn id="1" name="ID"/><tableColumn id="2" name="Name"/></tableColumns><tableStyleInfo name="TableStyleLight9" showFirstColumn="0" showLastColumn="0" showRowStripes="1" showColumnStripes="0"/></table>

另外,如果我打开 Excel 存档,它在 Apache POI 创建的文件夹中没有主题文件夹,但在 Office Excel 中手动创建的文件夹中却存在该主题文件夹。奇怪的。

更新2: 示例可执行代码(使用 Netbeans):

/*
 * To change this license header, choose License Headers in Project Properties.
 * To change this template file, choose Tools | Templates
 * and open the template in the editor.
 */

package apachepoi_exceltest;

    import java.io.File;
    import java.io.FileOutputStream;
    import java.io.IOException;
    import java.util.HashMap;
    import java.util.Map;
    import org.apache.poi.ss.util.AreaReference;
    import org.apache.poi.ss.util.CellRangeAddress;
    import org.apache.poi.ss.util.CellReference;
    import org.apache.poi.xssf.usermodel.XSSFRow;
    import org.apache.poi.xssf.usermodel.XSSFSheet;
    import org.apache.poi.xssf.usermodel.XSSFTable;
    import org.apache.poi.xssf.usermodel.XSSFWorkbook;
    import org.openxmlformats.schemas.spreadsheetml.x2006.main.CTTable;
    import org.openxmlformats.schemas.spreadsheetml.x2006.main.CTTableColumn;
    import org.openxmlformats.schemas.spreadsheetml.x2006.main.CTTableColumns;
    import org.openxmlformats.schemas.spreadsheetml.x2006.main.CTTableStyleInfo;

    /**
     *
     */
    public class ApachePOI_ExcelTest {

        /**
         * @param args the command line arguments
         */
        public static void main(String[] args) {

            String outputDir = "Your Local Directory Here";

            // TODO code application logic here
            HashMap<String, String> dataMap = new HashMap<>();

            dataMap.put("ID 1", "Dummy Name 1");
            dataMap.put("ID 2", "Dummy Name 2");
            dataMap.put("ID 3", "Dummy Name 3");
            dataMap.put("ID 4", "Dummy Name 4");

            writeExcel(dataMap, outputDir);

        }

        private static void writeExcel(HashMap<String, String> dataMap, String outputDir) {
            System.out.println("Writing Excel(*.xlsx) Summary File...");
            XSSFWorkbook workbook = null;
            try {

                // Number of columns
                int numColumns = 2; // ID and Name
                // Number of rows
                int numRows = dataMap.size() + 1; // +1 for header

                // Create Workbook
                workbook = new XSSFWorkbook();

                // Create Excel Table
                XSSFSheet sheet = workbook.createSheet("Summary");
                XSSFTable table = sheet.createTable();
                table.setDisplayName("Test");
                CTTable cttable;
                cttable = table.getCTTable();

                // Style configurations
                CTTableStyleInfo style = cttable.addNewTableStyleInfo();
                style.setName("TableStyleMedium16");
                style.setShowColumnStripes(false);
                style.setShowRowStripes(true);

                // Set Tabel Span Area
                AreaReference reference = new AreaReference(new CellReference(0, 0), new CellReference(numRows - 1, numColumns - 1));
                cttable.setRef(reference.formatAsString());
                cttable.setId(1);
                cttable.setName("Test");
                cttable.setDisplayName("Test");
                cttable.setTotalsRowCount(numRows);
                cttable.setTotalsRowShown(false);

                // Create Columns
                CTTableColumns columns = cttable.addNewTableColumns();
                columns.setCount(numColumns);

                // Create Column, Row, Cell Objects
                CTTableColumn column;
                XSSFRow row;

                // Add ID Header
                column = columns.addNewTableColumn();
                column.setName("Column" + (1));
                column.setId(1);

                // Add Name Header
                column = columns.addNewTableColumn();
                column.setName("Column" + (1));
                column.setId(1);

                // Add Header Row
                XSSFRow headerRow = sheet.createRow(0);
                headerRow.createCell(0).setCellValue("ID");
                headerRow.createCell(1).setCellValue("Name");

                int rowNumber = 1;
                for (Map.Entry<String, String> entry : dataMap.entrySet()) {
                    String id = entry.getKey();
                    String name = entry.getValue();
                    row = sheet.createRow(rowNumber);
                    row.createCell(0).setCellValue(id);
                    row.createCell(1).setCellValue(name);
                    rowNumber++;
                }

                // Set Filter (Below three lines code somehow not working in this example, so setting AutoFilter to WorkSheet)
    //             CTAutoFilter fltr = CTAutoFilter.Factory.newInstance();
    //             fltr.setRef((new AreaReference(new CellReference(0, 0), new CellReference(numRows - 1, numColumns - 1))).formatAsString());
    //             cttable.setAutoFilter(fltr);
                sheet.setAutoFilter(CellRangeAddress.valueOf((new AreaReference(new CellReference(0, 0), new CellReference(numRows - 1, numColumns - 1))).formatAsString()));

                // Freeze First Row as header Row
                sheet.createFreezePane(0, 1, 0, 2);

            } catch (Exception ex) {
                System.out.println("Error while writing Excel summary file!");
            } finally {
                try {
                    // Lets write the Excel File Now
                    if (workbook != null) {
                        String excelDir = outputDir + File.separator + "workbook.xlsx";
                        try (final FileOutputStream out = new FileOutputStream(excelDir)) {
                            workbook.write(out);
                        }
                    }
                } catch (IOException ex) {
                    System.out.println("IO Error while writing Excel summary file!");
                }
            }
        }

    }

使用的库:

ooxml-schemas-1.1.jar

poi-3.11-beta2-20140822.jar

poi-ooxml-3.11-beta2-20140822.jar

xmlbeans-2.6.0.jar


您的代码的问题在于存在一行。 “cttable.setTotalsRowCount(行数);” 删除它,一切都会正常。 如果有疑问,请将在 Excel 中手动创建的某些工作表的 XML 定义与使用 Apache POI 创建的定义进行比较

本文内容由网友自发贡献,版权归原作者所有,本站不承担相应法律责任。如您发现有涉嫌抄袭侵权的内容,请联系:hwhale#tublm.com(使用前将#替换为@)

使用 Apache POI 将结果集转换为 Excel (*.xlsx) 表 的相关文章

  • 如果测试用例失败,Selenium Web 驱动程序无法关闭 Firefox 实例

    我各位 我正在使用 junit 和 selenium web 驱动程序 2 28 问题是 如果我运行成功的测试用例 Web 驱动器能够关闭 Firefox 实例 但是当测试用例失败时 Selenium Web 驱动器无法关闭 Firefox
  • JavaMail Gmail 问题。 “准备启动 TLS”然后失败

    mailServerProperties System getProperties mailServerProperties put mail smtp port 587 mailServerProperties put mail smtp
  • 在Windows上安装Java 11 OpenJDK(系统路径问题)

    Java 11 最近发布了 众所周知 这个版本没有安装文件 当然 要在没有安装程序的情况下安装 Java 我将系统设置 PATH 和 JAVA HOME 设置为解压缩 Java 11 的文件夹的地址 根据对类似问题的已接受回复建议 唯一的事
  • CXF Swagger2功能添加安全定义

    我想使用 org apache cxf jaxrs swagger Swagger2Feature 将安全定义添加到我的其余服务中 但是我看不到任何相关方法或任何有关如何执行此操作的资源 下面是我想使用 swagger2feature 生成
  • 在浏览器中点击应用程序时播放框架挂起

    我正在 Play 中运行一个应用程序activator run 也许 5 次中有 3 次 它会挂起 当我去http localhost 9000 它就永远坐在那里旋转 我看到很多promise timed out错误也 我应该去哪里寻找这个
  • 一种使用 Java Robot API 和 Selenium WebDriver by Java 进行文件上传的解决方案

    我看到很多人在使用 Selenium WebDriver 的测试环境中上传文件时遇到问题 我使用 selenium WebDriver 和 java 也遇到了同样的问题 我终于找到了解决方案 所以我将其发布在这里希望对其他人有所帮助 当我需
  • 请求位置更新参数

    这就是 requestLocationUpdates 的样子 我使用它的方式 requestLocationUpdates String provider long minTime float minDistance LocationLis
  • Clip 在 Java 中播放 WAV 文件时出现严重延迟

    我编写了一段代码来读取 WAV 文件 大小约为 80 mb 并播放该文件 问题是声音播放效果很差 极度滞后 你能告诉我有什么问题吗 这是我的代码 我称之为doPlayJframe 构造函数内的函数 private void doPlay f
  • Spring Data 与 Spring Data JPA 与 JdbcTemplate

    我有信心Spring Data and Spring Data JPA指的是相同的 但后来我在 youtube 上观看了一个关于他正在使用JdbcTemplate在那篇教程中 所以我在那里感到困惑 我想澄清一下两者之间有什么区别Spring
  • 制作java包

    我的 Java 类组织变得有点混乱 所以我要回顾一下我在 Java 学习中跳过的东西 类路径 我无法安静地将心爱的类编译到我为它们创建的包中 这是我的文件夹层次结构 com david Greet java greeter SayHello
  • 启动时的 Excel 加载项

    我正在使用 Visual C 创建 Microsoft Excel 的加载项 当我第一次创建解决方案时 它包含一个名为 ThisAddIn Startup 的函数 我在这个函数中添加了以下代码 private void ThisAddIn
  • 将 JSON 参数从 java 发布到 sinatra 服务

    我有一个 Android 应用程序发布到我的 sinatra 服务 早些时候 我无法读取 sinatra 服务上的参数 但是 在我将内容类型设置为 x www form urlencoded 之后 我能够看到参数 但不完全是我想要的 我在
  • 如何在 Maven 中显示消息

    如何在 Maven 中显示消息 在ant中 我们确实有 echo 来显示消息 但是在maven中 我该怎么做呢 您可以使用 antrun 插件
  • 如何配置eclipse以保持这种代码格式?

    以下代码来自 playframework 2 0 的示例 Display the dashboard public static Result index return ok dashboard render Project findInv
  • 查看Jasper报告执行的SQL

    运行 Jasper 报表 其中 SQL 嵌入到报表文件 jrxml 中 时 是否可以看到执行的 SQL 理想情况下 我还想查看替换每个 P 占位符的值 Cheers Don JasperReports 使用 Jakarta Commons
  • 休眠以持久保存日期

    有没有办法告诉 Hibernate java util Date 应该持久保存 我需要这个来解决 MySQL 中缺少的毫秒分辨率问题 您能想到这种方法有什么缺点吗 您可以自己创建字段long 或者使用自定义的UserType 实施后User
  • 如何修复“sessionFactory”或“hibernateTemplate”是必需的问题

    我正在使用 Spring Boot JPA WEB 和 MYSQL 创建我的 Web 应用程序 它总是说 sessionFactory or hibernateTemplate是必需的 我该如何修复它 我已经尝试过的东西 删除了本地 Mav
  • com.jcraft.jsch.JSchException:身份验证失败

    当我从本地磁盘上传文件到远程服务器时 出现这样的异常 com jcraft jsch JSchException Auth fail at org apache tools ant taskdefs optional ssh Scp exe
  • KeyPressed 和 KeyTyped 混淆[重复]

    这个问题在这里已经有答案了 我搜索过之间的区别KeyPressedand KeyTyped事件 但我仍然不清楚 我发现的一件事是 Keypressed 比 KeyTyped 首先被触发 请澄清一下这些事件何时被准确触发 哪个适合用于哪个目的
  • Jackson 将单个项目反序列化到列表中

    我正在尝试使用一项服务 该服务为我提供了一个带有数组字段的实体 id 23233 items name item 1 name item 2 但是 当数组包含单个项目时 将返回该项目本身 而不是包含一个元素的数组 id 43567 item

随机推荐

  • 是否可以使用 params 通过使用yield 的函数通过 ref 传递变量

    如果我有一个方法params参数 是否可以通过引用传递并在每次调用yield 时更新 像这样的事情 public static void GetRowsIter ref params valuesToUpdate foreach row i
  • Android gridview 在片段适配器构造函数中丢失

    我正在尝试实现图像网格 我在一项活动中通过参考这个做到了这一点link http developer android com guide topics ui layout gridview html example现在 如果我尝试在扩展 F
  • 将状态传递给函数指针

    我正在使用具有此类型的外部库中的函数 int libraryFunction int fp int 但是 我还需要将回调传递给ostream 并且库函数没有任何允许函子 lambda 或传递额外参数的重载 有没有办法获得ostream进入回
  • Qt + win32 + mingw 上的原生 Windows API 链接问题

    我正在尝试使用 mingw 工具集将本机 Windows API 与 Qt 结合使用 部分功能存在链接问题 会发生什么 这是 mingw 名称修改的错误吗 ifdef Q WS WIN HWND hwnd QWidget winId HDC
  • 用于匹配 Apache 虚拟主机文件中的特定值的正则表达式

    我想匹配定义为的值ServerName ServerAlias and DocumentRoot用正则表达式 任何带有前缀的内容 可以忽略 我还想将每个虚拟主机的定义分开 因此在下面的示例中我有两个数组 Example
  • UIImagePickerController 允许编辑错误地裁剪图像,在顶部留下黑条

    我在 iPad 上的弹出窗口中使用 UIImagePickerController 用前置摄像头拍照 我将 允许编辑 设置为 是 并在拍照后获得令人敬畏的内置 移动和缩放 视图 尽管图像被裁剪为 320x320 的正方形 但此视图中的裁剪矩
  • 如何包含塞尔维亚语的 2 种变体?带有拉丁字母和西里尔字母

    我有一个 Android 应用程序 我想翻译成塞尔维亚语 并且我想要该语言的两种变体 拉丁字母和西里尔字母 我尝试过这个变体 value sr rRS Latn value sr Latn value sr rRS Cyrl value s
  • 登录成功后如何开始新的活动?

    我想在登录成功后开始一项新活动 也就是说 当登录正确时 新的活动应该自动启动 我不知道在哪里提到启动活动 请帮我解决这个问题 我是 Android 新手 这是我的代码 public class BackgroundTask extends
  • UIScrollView 移动到导航和状态栏下方

    我有包含滚动视图的视图 当视图显示时 图像会以全屏 320x480 形式显示 隐藏状态栏和导航栏 当我点击屏幕时 状态和导航栏出现在屏幕上 但是这个东西将 UIScrollView 移到了导航栏下方 我希望状态和导航栏显示在我的滚动视图上
  • 如何在 IntelliJ IDEA 13 中创建 JAXB 项目?

    我正在学习JAXB 我需要知道如何在 IntelliJ IDEA13 中为 JAX B 创建一个简单的 java 项目 如果有人有想法 请更新我并使用 IDEA 的任何插件更新我 Thanks 创建项目时 您无需执行任何特殊操作 只需一个简
  • 像在 Windows 7 中一样在进度条中进行一些渐变无限移动

    我想知道是否可以仅使用 CSS3 功能在 div 内从左到右无休止地进行渐变移动 不需要支持所有浏览器 我只是想尝试一下 示例是蓝色进度条顶部的闪亮效果 举一个例子表示赞赏 使用这个CSS你可以让渐变无限移动 基于link http www
  • 是否有更好的方法来实现可继承的方法,该方法返回继承该类类型的对象?

    我正在尝试创建一个基类 它指定一个返回的方法 比如它自己类型的列表 我希望这个方法能够在继承类上正确工作 即 返回继承类的列表 这是我能想到的唯一方法 public abstract class Base
  • Postgres 在并发更新插入时出现死锁

    我们有一个从数据流中读取信息并将该信息更新到数据库中的应用程序 数据是 Google Drive 上发生的变化 这意味着影响相同对象的许多事件可能会非常接近地发生 将此信息更新插入数据库时 我们遇到了死锁 日志中显示的内容如下 我已经重建并
  • Java AWT/Swing:获取有关窗口位置/大小变化的通知

    我有一个窗口 我希望在位置或大小发生变化时收到通知 哪种类型的听众最适合 WindowListener不适合我 您可以使用组件监听器 http docs oracle com javase tutorial uiswing events c
  • Django 说端口已被使用

    当我运行 Django 时runserver命令显示端口已在使用中 所以每次我都需要杀死使用该端口的进程并再次运行服务器 谁能给我一个永久的解决方案 您可以使用另一个端口 因为可能是port您正在使用的有一些问题 python manage
  • 通过反射获取给定类的可访问方法列表

    有没有办法获取给定类可访问 不一定是公共 的方法列表 有问题的代码将属于完全不同的类 Example public class A public void methodA1 protected void methodA2 void meth
  • 无法在 Mac 上将 JanusGraph 连接到本地 Cassandra

    我已在 Mac OS X 10 11 6 上安装并运行 Cassandra 3 11 1 跑步cqlsh在终端中打印以下消息 Connected to Test Cluster at 127 0 0 1 9042 cqlsh 5 0 1 C
  • Android 在 ListView 中获取精确的滚动位置

    我想获得 ListView 滚动的确切像素位置 不 我指的不是第一个可见位置 有办法实现这一点吗 好的 我找到了一个解决方法 使用以下代码 View c listview getChildAt 0 int scrolly c getTop
  • 内部框架与新的 C# 技术

    如果我们开发了自己的 ORM 框架 并且该框架多年来运行良好 那么我们为什么要学习和使用全新的 net 技术 例如LINQ or Entity Framework or NHibernate or CSLA NET对于我们即将进行的软件项目
  • 使用 Apache POI 将结果集转换为 Excel (*.xlsx) 表

    我正在尝试写结果集到 Excel xlsx 表使用 Apache Poi Office Excel 中的无效表对象错误 但是 即使它写入 Excel 文件时没有任何错误 但当我尝试在 Office Excel 2013 中打开它时 它会显示