如何为使用WorkbookFactory创build的工作簿创buildCellStyle?

我正在一个java代码,我必须比较两个Excel表格,无论格式(xls或xlsx),并复制不同的行到一个新的Excel工作表。 然后我读了关于这两种格式的WorkbookFactory。 下面是我创build的代码片段:请帮助!

import org.apache.poi.ss.usermodel.Workbook; import org.apache.poi.ss.usermodel.WorkbookFactory; import org.apache.poi.xssf.usermodel.XSSFWorkbook; import org.apache.poi.ss.usermodel.CellStyle; import org.apache.poi.ss.usermodel.IndexedColors; class Compare extends CopyRow { //<-------VARIABLES DECLARATION & INITIALISATION-----> Workbook outputWorkbook,workbook1,workbook2; Sheet excel1Sheet,excel2Sheet,newSheet; public void compare(String fileA,String fileB) { try { if(fileA.endsWith(".xls")outputWorkbook = new XSSFWorkbook(new FileInputStream("C:/Documents and Settings/eclipse/workspace/CompareExcelV2/output.xls")); else outputWorkbook = new XSSFWorkbook(new FileInputStream("C:/Documents and Settings/eclipse/workspace/CompareExcelV2/output.xlsx")) workbook1 = WorkbookFactory.create(new File(fileA)); workbook2 = WorkbookFactory.create(new File(fileB)); CellStyle excel1Red = new workbook1.createCellStyle(); **//ERROR HERE** CellStyle excel2Green = new workbook2.createCellStyle(); **//ERROR HERE** CellStyle newStyle = new outputWorkbook.createCellStyle();**//ERROR HERE** } catch {} 

}

我无法创buildCellStyle。 我得到以下错误:

workbook1 cannot be resolved to a type

workbook2 cannot be resolved to a type

outputWorkbook cannot be resolved to a type

如果我们拿你的代码:

 if(fileA.endsWith(".xls")outputWorkbook = new XSSFWorkbook(new FileInputStream("C:/Documents and Settings/eclipse/workspace/CompareExcelV2/output.xls")); else outputWorkbook = new XSSFWorkbook(new FileInputStream("C:/Documents and Settings/eclipse/workspace/CompareExcelV2/output.xlsx")) workbook1 = WorkbookFactory.create(new File(fileA)); workbook2 = WorkbookFactory.create(new File(fileB)); 

那么有几件事情。 一个是从文件开放比从一个stream低内存 ,第二个是你的代码似乎没有做你想做的。 您似乎打开基于文件的outputWorkbook ,当我怀疑你只是想要一个新的空的,你以后保存。 相反,怎么样的东西:

 final String path = "C:/Documents and Settings/eclipse/workspace/CompareExcelV2/"; Workbook outputWorkbook; FileOutputStream outputTo; if (fileA.endsWith(".xls") { outputWorkbook = new HSSFWorkbook(); outputTo = new FileOutputStream(path + "output.xls"); } else { outputWorkbook = new XSSFWorkbook(); outputTo = new FileOutputStream(path + "output.xlsx"); } Workbook workbook1 = WorkbookFactory.create(new File(fileA)); Workbook workbook2 = WorkbookFactory.create(new File(fileB)); 

最后,请确保您的类path中包含所有正确的jar包,请参阅POI网站上的Components及其Dependencies部分以获取详细信息