我正在编写一个java代码,我必须比较两个excel表,无论格式如何(xls或xlsx),并复制与新excel表不同的行。然后我读到了可以接受这两种格式的WorkbookFactory。 以下是我创建的代码段:请帮助!!
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 {}
}
我无法创建CellStyle。我收到以下错误:
workbook1 cannot be resolved to a type
workbook2 cannot be resolved to a type
outputWorkbook cannot be resolved to a type
答案 0 :(得分:1)
如果我们接受您的代码:
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));
然后还有一些事情。一个是opening from a File is lower memory than from a 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));
最后,请确保您的类路径中包含所有正确的jar,有关详细信息,请参阅POI网站上的the Components and their Dependencies section