gpt4 book ai didi

java - 如何为使用 WorkbookFactory 创建的工作簿创建 CellStyle?

转载 作者:行者123 更新时间:2023-12-01 12:52:10 24 4
gpt4 key购买 nike

我正在编写一个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 无法解析为类型

workbook2 无法解析为类型

outputWorkbook 无法解析为类型

最佳答案

如果我们获取您的代码:

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,请参阅 the Components and their Dependencies section详情请访问 POI 网站

关于java - 如何为使用 WorkbookFactory 创建的工作簿创建 CellStyle?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/24138783/

24 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com