How to convert HSSFWorkbook to XSSFWorkbook using Apache POI?

匿名 (未验证) 提交于 2019-12-03 08:52:47

问题:

How to convert

org.apache.poi.hssf.usermodel.HSSFWorkbook

to

org.apache.poi.xssf.usermodel.XSSFWorkbook

in Apache POI?

Environment :

  • JSE1.6
  • JBossAS 4.3.2
  • POI 3.7

回答1:

this code has been adapted from what I found here on coderanch forum

public final class ExcelDocumentConverter { public static XSSFWorkbook convertWorkbookHSSFToXSSF(HSSFWorkbook source) {     XSSFWorkbook retVal = new XSSFWorkbook();     for (int i = 0; i  styleMap = (copyStyle) ? new HashMap() : null;     for (int i = source.getFirstRowNum(); i  maxColumnNum) {                 maxColumnNum = srcRow.getLastCellNum();             }         }     }     for (int i = 0; i  styleMap) {     // manage a list of merged zone in order to not insert two times a     // merged zone     Set mergedRegions = new TreeSet();     destRow.setHeight(srcRow.getHeight());     // pour chaque row     for (int j = srcRow.getFirstCellNum(); j  styleMap) {     if (styleMap != null) {         int stHashCode = oldCell.getCellStyle().hashCode();         HSSFCellStyle sourceCellStyle = styleMap.get(stHashCode);         XSSFCellStyle destnCellStyle = newCell.getCellStyle();         if (sourceCellStyle == null) {             sourceCellStyle = oldCell.getSheet().getWorkbook().createCellStyle();         }         destnCellStyle.cloneStyleFrom(oldCell.getCellStyle());         styleMap.put(stHashCode, sourceCellStyle);         newCell.setCellStyle(destnCellStyle);     }     switch (oldCell.getCellType()) {     case HSSFCell.CELL_TYPE_STRING:         newCell.setCellValue(oldCell.getStringCellValue());         break;     case HSSFCell.CELL_TYPE_NUMERIC:         newCell.setCellValue(oldCell.getNumericCellValue());         break;     case HSSFCell.CELL_TYPE_BLANK:         newCell.setCellType(HSSFCell.CELL_TYPE_BLANK);         break;     case HSSFCell.CELL_TYPE_BOOLEAN:         newCell.setCellValue(oldCell.getBooleanCellValue());         break;     case HSSFCell.CELL_TYPE_ERROR:         newCell.setCellErrorValue(oldCell.getErrorCellValue());         break;     case HSSFCell.CELL_TYPE_FORMULA:         newCell.setCellFormula(oldCell.getCellFormula());         break;     default:         break;     }  }  /**  * Récupère les informations de fusion des cellules dans la sheet source  * pour les appliquer à la sheet destination... Récupère toutes les zones  * merged dans la sheet source et regarde pour chacune d'elle si elle se  * trouve dans la current row que nous traitons. Si oui, retourne l'objet  * CellRangeAddress.  *   * @param sheet  *            the sheet containing the data.  * @param rowNum  *            the num of the row to copy.  * @param cellNum  *            the num of the cell to copy.  * @return the CellRangeAddress created.  */ public static CellRangeAddress getMergedRegion(HSSFSheet sheet, int rowNum, short cellNum) {     for (int i = 0; i  mergedRegions) {     return !mergedRegions.contains(newMergedRegion); } }


回答2:

Since all of the above answers don't help, here is working code:

Just write a main method that fills the necessary fields and uses transform().

package myStuff;  import java.io.*; import java.util.*;  import org.apache.poi.hssf.usermodel.*; import org.apache.poi.poifs.filesystem.POIFSFileSystem; import org.apache.poi.ss.usermodel.*; import org.apache.poi.ss.util.CellRangeAddress; import org.apache.poi.xssf.usermodel.*;  public class ExcelConverter {  private File path = null; private ArrayList inputFiles = new ArrayList(); private HSSFWorkbook workbookOld = null; private XSSFWorkbook workbookNew = null; private int lastColumn = 0; private HashMap styleMap = null;  private void getInputFiles() {     String call = "getInputFiles ";     if (this.path.isFile()) {         if (this.path.getAbsolutePath().endsWith(".xls")                 && !new File(this.path.getAbsolutePath() + "x").exists())             this.inputFiles.add(this.path);         else {             System.out                     .println("Datei endet nicht mit .xls oder XLSX-Datei existiert bereits");         }     } else         for (File f : this.path.listFiles(new FilenameFilter() {             // anonyme innere Klasse              @Override             public boolean accept(File dir, String name) {                 if (name.endsWith(".xls"))                     return true;                 return false;             }          })) {             if (!new File(f.getAbsoluteFile() + "x").exists()) {                 this.inputFiles.add(f);             }         }     System.out             .println(call + "Dateien gefunden: " + this.inputFiles.size());     System.out.println(call + "abgeschlossen"); }  private HSSFWorkbook getWorkBook(File f) throws FileNotFoundException,         IOException {     System.out.println("getWorkBook lese " + f.getAbsolutePath());     POIFSFileSystem fs = new POIFSFileSystem(new BufferedInputStream(             new FileInputStream(f)));     HSSFWorkbook workbook = new HSSFWorkbook(fs);     System.out.println("getWorkBook abgeschlossen");     return workbook; }  private void transform() {     String call = "transform ";     System.out.println(call + "Workbook");     XSSFSheet sheetNew;     HSSFSheet sheetOld;     this.workbookNew.setForceFormulaRecalculation(this.workbookOld             .getForceFormulaRecalculation());     // workbookNew.setHidden(workbookOld.isHidden()); //ST@03.05.2012 -     // von Apache noch nicht implementiert     this.workbookNew.setMissingCellPolicy(this.workbookOld             .getMissingCellPolicy());      for (int i = 0; i 

Now someone treat me to lunch for that :)



回答3:

//Added xbean-2.3.0.jar/xmlbeans-2.3.0.jar,poi-ooxml-3.7-20101029.jarpoi-ooxml-schemas-3.7-beta1.jar, import java.io.*; import java.util.*;  import org.apache.poi.hssf.usermodel.*; import org.apache.poi.poifs.filesystem.POIFSFileSystem; import org.apache.poi.ss.usermodel.*; import org.apache.poi.ss.util.CellRangeAddress; import org.apache.poi.xssf.usermodel.*;  public class Xls2Xlsx {  private File path = new File("c:/Integration-TestCases.xls"); private ArrayList inputFiles = new ArrayList();  private int lastColumn = 0; private HashMap styleMap = new HashMap();  private void getInputFiles() {     String call = "getInputFiles ";     if (this.path.isFile()) {         if (this.path.getAbsolutePath().endsWith(".xls")                 && !new File(this.path.getAbsolutePath() + "x").exists())             this.inputFiles.add(this.path);         else {             System.out                     .println("Datei endet nicht mit .xls oder XLSX-Datei existiert bereits");         }     } else         for (File f : this.path.listFiles(new FilenameFilter() {             // anonyme innere Klasse              @Override             public boolean accept(File dir, String name) {                 if (name.endsWith(".xls"))                     return true;                 return false;             }          })) {             if (!new File(f.getAbsoluteFile() + "x").exists()) {                 this.inputFiles.add(f);             }         }     System.out             .println(call + "Dateien gefunden: " + this.inputFiles.size());     System.out.println(call + "abgeschlossen"); }  private HSSFWorkbook getWorkBook(File f) throws FileNotFoundException,         IOException {     System.out.println("getWorkBook lese " + f.getAbsolutePath());     POIFSFileSystem fs = new POIFSFileSystem(new BufferedInputStream(             new FileInputStream(f)));     HSSFWorkbook workbook = new HSSFWorkbook(fs);     System.out.println("getWorkBook abgeschlossen");     return workbook; }  private void transformHSSF(HSSFWorkbook workbookOld ,XSSFWorkbook workbookNew) {     String call = "transform ";     System.out.println(call + "Workbook");     XSSFSheet sheetNew;     HSSFSheet sheetOld;     //TODO::workbookNew.setForceFormulaRecalculation(workbookOld.getForceFormulaRecalculation());     // workbookNew.setHidden(workbookOld.isHidden()); //ST@03.05.2012 -     // von Apache noch nicht implementiert     workbookNew.setMissingCellPolicy(workbookOld.getMissingCellPolicy());      for (int i = 0; i 


回答4:

See the article Upgrading to POI 3.5, including converting existing HSSF Usermodel code to SS Usermodel (for XSSF and HSSF). There's an example here.



回答5:

Seems to me like you should use the 'SS Usermodel'. See Apache POI's website for more on the subject.



回答6:

//Added xbean-2.3.0.jar/xmlbeans-2.3.0.jar,poi-ooxml-3.7-20101029.jarpoi-ooxml-schemas-3.7-beta1.jar,   import java.io.*; import java.util.*;  import org.apache.poi.hssf.usermodel.*; import org.apache.poi.poifs.filesystem.POIFSFileSystem; import org.apache.poi.ss.usermodel.*; import org.apache.poi.ss.util.CellRangeAddress; import org.apache.poi.xssf.usermodel.*;  public class Xlsx2Xls {  private File path = new File("c:/Integration-TestCases.xls"); private ArrayList inputFiles = new ArrayList();  private int lastColumn = 0; private HashMap styleMap = new HashMap();  private void getInputFiles() {     String call = "getInputFiles ";     if (this.path.isFile()) {         if (this.path.getAbsolutePath().endsWith(".xls")                 && !new File(this.path.getAbsolutePath() + "x").exists())             this.inputFiles.add(this.path);         else {             System.out                     .println("Datei endet nicht mit .xls oder XLSX-Datei existiert bereits");         }     } else         for (File f : this.path.listFiles(new FilenameFilter() {             // anonyme innere Klasse              @Override             public boolean accept(File dir, String name) {                 if (name.endsWith(".xls"))                     return true;                 return false;             }          })) {             if (!new File(f.getAbsoluteFile() + "x").exists()) {                 this.inputFiles.add(f);             }         }     System.out             .println(call + "Dateien gefunden: " + this.inputFiles.size());     System.out.println(call + "abgeschlossen"); }  private HSSFWorkbook getWorkBook(File f) throws FileNotFoundException,         IOException {     System.out.println("getWorkBook lese " + f.getAbsolutePath());     POIFSFileSystem fs = new POIFSFileSystem(new BufferedInputStream(             new FileInputStream(f)));     HSSFWorkbook workbook = new HSSFWorkbook(fs);     System.out.println("getWorkBook abgeschlossen");     return workbook; }  private void transformXSSF(XSSFWorkbook workbookOld ,HSSFWorkbook workbookNew) {     String call = "transform ";     System.out.println(call + "Workbook");     HSSFSheet sheetNew;     XSSFSheet sheetOld;     //TODO::workbookNew.setForceFormulaRecalculation(workbookOld.getForceFormulaRecalculation());     // workbookNew.setHidden(workbookOld.isHidden()); //ST@03.05.2012 -     // von Apache noch nicht implementiert     workbookNew.setMissingCellPolicy(workbookOld.getMissingCellPolicy());      for (int i = 0; i 


回答7:

Here is my approach

import java.util.ArrayList; import java.util.Iterator; import java.util.List; import java.util.Set; import java.util.TreeSet;  import org.apache.poi.hssf.usermodel.HSSFCell; import org.apache.poi.hssf.usermodel.HSSFClientAnchor; import org.apache.poi.hssf.usermodel.HSSFPatriarch; import org.apache.poi.hssf.usermodel.HSSFPicture; import org.apache.poi.hssf.usermodel.HSSFPictureData; import org.apache.poi.hssf.usermodel.HSSFRow; import org.apache.poi.hssf.usermodel.HSSFShape; import org.apache.poi.hssf.usermodel.HSSFSheet; 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.ClientAnchor; import org.apache.poi.ss.usermodel.CreationHelper; import org.apache.poi.ss.usermodel.DataFormat; import org.apache.poi.ss.usermodel.Drawing; import org.apache.poi.ss.usermodel.Font; import org.apache.poi.ss.usermodel.Footer; import org.apache.poi.ss.usermodel.Header; import org.apache.poi.ss.usermodel.Name; import org.apache.poi.ss.usermodel.PrintSetup; import org.apache.poi.ss.usermodel.Sheet; import org.apache.poi.ss.util.CellRangeAddress; import org.apache.poi.ss.util.CellReference; import org.apache.poi.xssf.usermodel.XSSFCell; import org.apache.poi.xssf.usermodel.XSSFClientAnchor; import org.apache.poi.xssf.usermodel.XSSFDrawing; import org.apache.poi.xssf.usermodel.XSSFName; import org.apache.poi.xssf.usermodel.XSSFPicture; import org.apache.poi.xssf.usermodel.XSSFPictureData; import org.apache.poi.xssf.usermodel.XSSFRow; import org.apache.poi.xssf.usermodel.XSSFShape; import org.apache.poi.xssf.usermodel.XSSFSheet; import org.apache.poi.xssf.usermodel.XSSFWorkbook; import org.openxmlformats.schemas.drawingml.x2006.spreadsheetDrawing.CTMarker; import org.openxmlformats.schemas.drawingml.x2006.spreadsheetDrawing.CTTwoCellAnchor;  public class XlsXlsxConverter3 { @SuppressWarnings("unused") private static class FormulaInfo {  private String sheetName; private Integer rowIndex; private Integer cellIndex; private String formula;  private FormulaInfo(String sheetName, Integer rowIndex, Integer cellIndex, String formula) { this
标签
易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!