java – 使用Apache POI将ResultSet转换为Excel(* .xlsx)表

前端之家收集整理的这篇文章主要介绍了java – 使用Apache POI将ResultSet转换为Excel(* .xlsx)表前端之家小编觉得挺不错的,现在分享给大家,也给大家做个参考。
我正在尝试使用Apache Poi将ResultSet写入Excel(* .xlsx)表.

Office Excel中的表对象错误无效

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

这是粗略的示例代码using this example

  1. public static void writeExcel(ResultSet rs,int sqliteRowCount,String dir) {
  2. System.out.println("Writing Excel(*.xlsx) File...");
  3. XSSFWorkbook workbook = null;
  4. try {
  5. if (rs != null) {
  6. // Get ResultSet MetaData
  7. ResultSetMetaData rsmd = rs.getMetaData();
  8. // Number of columns
  9. int numColumns = rsmd.getColumnCount();
  10. // Number of rows
  11. // + 1 for headers
  12. int numRows = sqliteRowCount + 1;
  13. workbook = new XSSFWorkbook();
  14.  
  15. // Create Excel Table
  16. XSSFSheet sheet = workbook.createSheet("Text");
  17. XSSFTable table = sheet.createTable();
  18. table.setDisplayName("Test");
  19. CTTable cttable;
  20. cttable = table.getCTTable();
  21.  
  22. // Style configurations
  23. CTTableStyleInfo style = cttable.addNewTableStyleInfo();
  24. style.setName("TableStyleMedium16");
  25. style.setShowColumnStripes(false);
  26. style.setShowRowStripes(true);
  27.  
  28. // Set Table Span Area
  29. AreaReference reference = new AreaReference(new CellReference(0,0),new CellReference(numRows - 1,numColumns - 1));
  30. cttable.setRef(reference.formatAsString());
  31. cttable.setId(1);
  32. cttable.setName("Test");
  33. cttable.setDisplayName("Test");
  34. cttable.setTotalsRowCount(numRows);
  35. cttable.setTotalsRowShown(false);
  36.  
  37. // Create Columns
  38. CTTableColumns columns = cttable.addNewTableColumns();
  39. columns.setCount(numColumns);
  40.  
  41. // Create Column,Row,Cell Objects
  42. CTTableColumn column;
  43. XSSFRow row;
  44.  
  45. // Add Header and Columns
  46. XSSFRow headerRow = sheet.createRow(0);
  47. for (int i = 0; i < numColumns; i++) {
  48. column = columns.addNewTableColumn();
  49. column.setName("Column" + (i + 1));
  50. column.setId(i + 1);
  51. headerRow.createCell(i).setCellValue(rsmd.getColumnLabel(i + 1));
  52. }
  53.  
  54. // Write each row from ResultSet
  55. int rowNumber = 1;
  56. while (rs.next()) {
  57. row = sheet.createRow(rowNumber);
  58. for (int y = 0; y < numColumns; y++) {
  59. row.createCell(y).setCellValue(rs.getString(y + 1));
  60. }
  61. rowNumber++;
  62. }
  63.  
  64. // Set AutoFilter
  65. CTAutoFilter fltr = CTAutoFilter.Factory.newInstance();
  66. fltr.setRef((new AreaReference(new CellReference(0,numColumns - 1))).formatAsString());
  67. cttable.setAutoFilter(fltr);
  68. // sheet.setAutoFilter(CellRangeAddress.valueOf((new AreaReference(new CellReference(0,numColumns - 1))).formatAsString()));
  69. // Freeze Pan
  70. sheet.createFreezePane(0,1,2);
  71. }
  72. } catch (sqlException ex) {
  73. System.out.println("sql Error while writing Excel file!");
  74. } finally {
  75. try {
  76. // Let's write the excel file now
  77. if (workbook != null) {
  78. String excelDir = dir + File.separator + "workbook.xlsx";
  79. try (final FileOutputStream out = new FileOutputStream(excelDir)) {
  80. workbook.write(out);
  81. }
  82. }
  83. } catch (IOException ex) {
  84. System.out.println("IO Error while writing Excel summary file!");
  85. }
  86. }
  87. }

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

更新1:

如果使用Apache POI创建,则在Excel存档中使用表格XML文件

  1. <?xml version="1.0" encoding="UTF-8"?>
  2. <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文件

  1. <?xml version="1.0" encoding="UTF-8" standalone="yes"?>
  2. <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):

  1. /*
  2. * To change this license header,choose License Headers in Project Properties.
  3. * To change this template file,choose Tools | Templates
  4. * and open the template in the editor.
  5. */
  6.  
  7. package apachepoi_exceltest;
  8.  
  9. import java.io.File;
  10. import java.io.FileOutputStream;
  11. import java.io.IOException;
  12. import java.util.HashMap;
  13. import java.util.Map;
  14. import org.apache.poi.ss.util.AreaReference;
  15. import org.apache.poi.ss.util.CellRangeAddress;
  16. import org.apache.poi.ss.util.CellReference;
  17. import org.apache.poi.xssf.usermodel.XSSFRow;
  18. import org.apache.poi.xssf.usermodel.XSSFSheet;
  19. import org.apache.poi.xssf.usermodel.XSSFTable;
  20. import org.apache.poi.xssf.usermodel.XSSFWorkbook;
  21. import org.openxmlformats.schemas.spreadsheetml.x2006.main.CTTable;
  22. import org.openxmlformats.schemas.spreadsheetml.x2006.main.CTTableColumn;
  23. import org.openxmlformats.schemas.spreadsheetml.x2006.main.CTTableColumns;
  24. import org.openxmlformats.schemas.spreadsheetml.x2006.main.CTTableStyleInfo;
  25.  
  26. /**
  27. *
  28. */
  29. public class ApachePOI_ExcelTest {
  30.  
  31. /**
  32. * @param args the command line arguments
  33. */
  34. public static void main(String[] args) {
  35.  
  36. String outputDir = "Your Local Directory Here";
  37.  
  38. // TODO code application logic here
  39. HashMap<String,String> dataMap = new HashMap<>();
  40.  
  41. dataMap.put("ID 1","Dummy Name 1");
  42. dataMap.put("ID 2","Dummy Name 2");
  43. dataMap.put("ID 3","Dummy Name 3");
  44. dataMap.put("ID 4","Dummy Name 4");
  45.  
  46. writeExcel(dataMap,outputDir);
  47.  
  48. }
  49.  
  50. private static void writeExcel(HashMap<String,String> dataMap,String outputDir) {
  51. System.out.println("Writing Excel(*.xlsx) Summary File...");
  52. XSSFWorkbook workbook = null;
  53. try {
  54.  
  55. // Number of columns
  56. int numColumns = 2; // ID and Name
  57. // Number of rows
  58. int numRows = dataMap.size() + 1; // +1 for header
  59.  
  60. // Create Workbook
  61. workbook = new XSSFWorkbook();
  62.  
  63. // Create Excel Table
  64. XSSFSheet sheet = workbook.createSheet("Summary");
  65. XSSFTable table = sheet.createTable();
  66. table.setDisplayName("Test");
  67. CTTable cttable;
  68. cttable = table.getCTTable();
  69.  
  70. // Style configurations
  71. CTTableStyleInfo style = cttable.addNewTableStyleInfo();
  72. style.setName("TableStyleMedium16");
  73. style.setShowColumnStripes(false);
  74. style.setShowRowStripes(true);
  75.  
  76. // Set Tabel Span Area
  77. AreaReference reference = new AreaReference(new CellReference(0,numColumns - 1));
  78. cttable.setRef(reference.formatAsString());
  79. cttable.setId(1);
  80. cttable.setName("Test");
  81. cttable.setDisplayName("Test");
  82. cttable.setTotalsRowCount(numRows);
  83. cttable.setTotalsRowShown(false);
  84.  
  85. // Create Columns
  86. CTTableColumns columns = cttable.addNewTableColumns();
  87. columns.setCount(numColumns);
  88.  
  89. // Create Column,Cell Objects
  90. CTTableColumn column;
  91. XSSFRow row;
  92.  
  93. // Add ID Header
  94. column = columns.addNewTableColumn();
  95. column.setName("Column" + (1));
  96. column.setId(1);
  97.  
  98. // Add Name Header
  99. column = columns.addNewTableColumn();
  100. column.setName("Column" + (1));
  101. column.setId(1);
  102.  
  103. // Add Header Row
  104. XSSFRow headerRow = sheet.createRow(0);
  105. headerRow.createCell(0).setCellValue("ID");
  106. headerRow.createCell(1).setCellValue("Name");
  107.  
  108. int rowNumber = 1;
  109. for (Map.Entry<String,String> entry : dataMap.entrySet()) {
  110. String id = entry.getKey();
  111. String name = entry.getValue();
  112. row = sheet.createRow(rowNumber);
  113. row.createCell(0).setCellValue(id);
  114. row.createCell(1).setCellValue(name);
  115. rowNumber++;
  116. }
  117.  
  118. // Set Filter (Below three lines code somehow not working in this example,so setting AutoFilter to WorkSheet)
  119. // CTAutoFilter fltr = CTAutoFilter.Factory.newInstance();
  120. // fltr.setRef((new AreaReference(new CellReference(0,numColumns - 1))).formatAsString());
  121. // cttable.setAutoFilter(fltr);
  122. sheet.setAutoFilter(CellRangeAddress.valueOf((new AreaReference(new CellReference(0,numColumns - 1))).formatAsString()));
  123.  
  124. // Freeze First Row as header Row
  125. sheet.createFreezePane(0,2);
  126.  
  127. } catch (Exception ex) {
  128. System.out.println("Error while writing Excel summary file!");
  129. } finally {
  130. try {
  131. // Lets write the Excel File Now
  132. if (workbook != null) {
  133. String excelDir = outputDir + File.separator + "workbook.xlsx";
  134. try (final FileOutputStream out = new FileOutputStream(excelDir)) {
  135. workbook.write(out);
  136. }
  137. }
  138. } catch (IOException ex) {
  139. System.out.println("IO Error while writing Excel summary file!");
  140. }
  141. }
  142. }
  143.  
  144. }

使用的库:

OOXML-模式-1.1.jar

POI-3.11-beta2-20140822.jar

POI-OOXML-3.11-beta2-20140822.jar

XMLBeans的-2.6.0.jar

解决方法

你的代码出了什么问题就是存在一行. “cttable.setTotalsRowCount(numRows行);” 删除它,一切都会工作. 如果有疑问,请比较在Excel中手动创建的某些工作表的XML定义以及使用Apache POI创建的定义

猜你在找的Java相关文章