我正在研究一個java代碼,我必須比較兩個excel表格,不管格式(xls或xlsx)如何,並複製不同於新Excel表格的行。然後我讀了WorkbookFactory,它可以接受這兩種格式。 下面是我創建的代碼片段:請幫助!如何爲使用WorkbookFactory創建的工作簿創建CellStyle?
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
感謝您的幫助! @Gagravarr我也發現了CellStyle的問題,我試圖使用(我的壞)'excel1Red = new workbook1.createCellStyle();來初始化CellStyle;'所以編譯器正在尋找一個名爲'workbook1'的構造函數。此外,workbookFactory不能創建一個新的Excel?它只能讀取excel文件?如果是這樣,如果我比較'.xls'和'.xlsx'文件,根據我的代碼,它將創建一個'.xls'輸出文件,因爲它是'fileA',所以在將輸出寫入輸出文件,因爲'fileB'。請賜教,我是Java和Apache POI的新手。提前致謝。 – jake295
'WorkbookFactory'根據給定的輸入創建適當類型的工作簿,使您無需檢查。對於輸出來說,如果你從一個新文件開始,只有你知道你想要什麼類型,所以你可以根據自己的需求/要求初始化一個適當的'HSSFWorkbook'或'XSSFWorkbook' – Gagravarr