[英]Copying Excel Worksheets in POI
有誰知道使用 POI 將工作表從一個工作簿復制到另一個工作簿的方法? Workbook 類有一個 cloneSheet 方法,但似乎無法將克隆的工作表插入到新工作簿中?
如果沒有可以輕松完成此操作的 API,是否有人擁有將所有數據(樣式、列寬、數據等)從一張工作表復制到另一張工作表的代碼?
jxls 有復制工作表的方法,但在工作簿之間復制時它們不起作用。
我已經用 poi 實現了一些功能。 請查看代碼供您參考。
import java.io.BufferedInputStream;
import java.io.BufferedOutputStream;
import java.io.FileInputStream;
import java.io.FileOutputStream;
import java.io.IOException;
import org.apache.poi.hssf.usermodel.HSSFCell;
import org.apache.poi.hssf.usermodel.HSSFRow;
import org.apache.poi.hssf.usermodel.HSSFSheet;
import org.apache.poi.hssf.usermodel.HSSFWorkbook;
public class ExcelReadAndWrite {
public static void main(String[] args) throws IOException {
ExcelReadAndWrite excel = new ExcelReadAndWrite();
excel.process("D:/LNN/My Workspace/POI/src/tables.xls");
}
public void process(String fileName) throws IOException {
BufferedInputStream bis = new BufferedInputStream(new FileInputStream(fileName));
HSSFWorkbook workbook = new HSSFWorkbook(bis);
HSSFWorkbook myWorkBook = new HSSFWorkbook();
HSSFSheet sheet = null;
HSSFRow row = null;
HSSFCell cell = null;
HSSFSheet mySheet = null;
HSSFRow myRow = null;
HSSFCell myCell = null;
int sheets = workbook.getNumberOfSheets();
int fCell = 0;
int lCell = 0;
int fRow = 0;
int lRow = 0;
for (int iSheet = 0; iSheet < sheets; iSheet++) {
sheet = workbook.getSheetAt(iSheet);
if (sheet != null) {
mySheet = myWorkBook.createSheet(sheet.getSheetName());
fRow = sheet.getFirstRowNum();
lRow = sheet.getLastRowNum();
for (int iRow = fRow; iRow <= lRow; iRow++) {
row = sheet.getRow(iRow);
myRow = mySheet.createRow(iRow);
if (row != null) {
fCell = row.getFirstCellNum();
lCell = row.getLastCellNum();
for (int iCell = fCell; iCell < lCell; iCell++) {
cell = row.getCell(iCell);
myCell = myRow.createCell(iCell);
if (cell != null) {
myCell.setCellType(cell.getCellType());
switch (cell.getCellType()) {
case HSSFCell.CELL_TYPE_BLANK:
myCell.setCellValue("");
break;
case HSSFCell.CELL_TYPE_BOOLEAN:
myCell.setCellValue(cell.getBooleanCellValue());
break;
case HSSFCell.CELL_TYPE_ERROR:
myCell.setCellErrorValue(cell.getErrorCellValue());
break;
case HSSFCell.CELL_TYPE_FORMULA:
myCell.setCellFormula(cell.getCellFormula());
break;
case HSSFCell.CELL_TYPE_NUMERIC:
myCell.setCellValue(cell.getNumericCellValue());
break;
case HSSFCell.CELL_TYPE_STRING:
myCell.setCellValue(cell.getStringCellValue());
break;
default:
myCell.setCellFormula(cell.getCellFormula());
}
}
}
}
}
}
}
bis.close();
BufferedOutputStream bos = new BufferedOutputStream(
new FileOutputStream("workbook.xls", true));
myWorkBook.write(bos);
bos.close();
}
}
我為 NPOI 創建了一個工作項: http ://npoi.codeplex.com/WorkItem/View.aspx?WorkItemId= 6057 。
更新:工作項在 NPOI 2.0 中實現。 您可以從https://npoi.codeplex.com/releases/view/112932下載 NPOI 2.0
如果您使用的是 Java POI 庫,最好將電子表格加載到內存中,然后創建一個新的電子表格並寫入您要復制的每條記錄……這不是最好的方法,而是完成了復制功能。 ..
這是我將工作簿從一個工作簿復制到另一個工作簿的實現。 這個解決方案對我有用。 如果工作表沒有表格等,此代碼將起作用。如果工作表包含簡單文本(字符串、布爾值、整數等)、公式,則此解決方案將起作用。
Workbook oldWB = new XSSFWorkbook(new FileInputStream("C:\\input.xlsx"));
Workbook newWB = new XSSFWorkbook();
CellStyle newStyle = newWB.createCellStyle(); // Need this to copy over styles from old sheet to new sheet. Next step will be processed below
Row row;
Cell cell;
for (int i = 0; i < oldWB.getNumberOfSheets(); i++) {
XSSFSheet sheetFromOldWB = (XSSFSheet) oldWB.getSheetAt(i);
XSSFSheet sheetForNewWB = (XSSFSheet) newWB.createSheet(sheetFromOldWB.getSheetName());
for (int rowIndex = 0; rowIndex < sheetFromOldWB.getPhysicalNumberOfRows(); rowIndex++) {
row = sheetForNewWB.createRow(rowIndex); //create row in this new sheet
for (int colIndex = 0; colIndex < sheetFromOldWB.getRow(rowIndex).getPhysicalNumberOfCells(); colIndex++) {
cell = row.createCell(colIndex); //create cell in this row of this new sheet
Cell c = sheetFromOldWB.getRow(rowIndex).getCell(colIndex, Row.CREATE_NULL_AS_BLANK ); //get cell from old/original WB's sheet and when cell is null, return it as blank cells. And Blank cell will be returned as Blank cells. That will not change.
if (c.getCellType() == Cell.CELL_TYPE_BLANK){
System.out.println("This is BLANK " + ((XSSFCell) c).getReference());
}
else { //Below is where all the copying is happening. First It copies the styles of each cell and then it copies the content.
CellStyle origStyle = c.getCellStyle();
newStyle.cloneStyleFrom(origStyle);
cell.setCellStyle(newStyle);
switch (c.getCellTypeEnum()) {
case STRING:
cell.setCellValue(c.getRichStringCellValue().getString());
break;
case NUMERIC:
if (DateUtil.isCellDateFormatted(cell)) {
cell.setCellValue(c.getDateCellValue());
} else {
cell.setCellValue(c.getNumericCellValue());
}
break;
case BOOLEAN:
cell.setCellValue(c.getBooleanCellValue());
break;
case FORMULA:
cell.setCellValue(c.getCellFormula());
break;
case BLANK:
cell.setCellValue("who");
break;
default:
System.out.println();
}
}
}
}
}
//Write over to the new file
FileOutputStream fileOut = new FileOutputStream("C:\\output.xlsx");
newWB.write(fileOut);
oldWB.close();
newWB.close();
fileOut.close();
如果您的要求是按原樣復制整張紙而不留下任何東西,在這種情況下,消除過程會更好,並且比上面的代碼更快,而且您不必擔心丟失公式、繪圖、表格、樣式、字體等.
XSSFWorkbook wb = new XSSFWorkbook("C:\\abc.xlsx");
for (int i = wb.getNumberOfSheets() - 1; i >= 0; i--) {
if (!wb.getSheetName(i).contentEquals("January")) //This is a place holder. You will insert your logic here to get the sheets that you want.
wb.removeSheetAt(i); //Just remove the sheets that don't match your criteria in the if statement above
}
FileOutputStream out = new FileOutputStream(new File("C:\\xyz.xlsx"));
wb.write(out);
out.close();
我花了大約一周的時間來使用 POI(使用 coderanch 上的最新代碼)來做到這一點 - 請注意代碼有缺陷(使用 TreeSet 存在問題,您需要將其替換為 HashMap),但即使在修復之后它會在公式上崩潰。
雖然有可能做到,但不得不依賴黑客代碼是一個可怕的提議。
根據您的需求/預算,您可能需要考慮咬緊牙關並為 aspose 付費 - http://www.aspose.com/doctest/java-components/aspose.cells-for-java/copy-move-worksheets-within -and-between-workbooks.html
它成功復制了工作表,包括格式、公式和保護規則。 我在 130 秒內完成了 300 張。 (300 x 90kb 工作簿,編譯成一本 15mb 工作簿)。 該演示是免費的,它只是在工作簿中添加了一張額外的表格,提醒您購買許可證。
最好的方法是打開文件並加載它。 如果您想要源 Excel 文件中的任何特定工作表,則只需刪除與預期工作表不匹配的工作表。
試試這個:
FileInputStream fis=new FileInputStream("D:\\SourceExcel.xls");
Workbook wb=WorkbookFactory.create(fis);
for (int i = wb.getNumberOfSheets() - 1; i >= 0; i--) {
if (!wb.getSheetName(i).contentEquals("SheetNameWhichwantToRetain")) //This is a place holder. You will insert your logic here to get the sheets that you want.
wb.removeSheetAt(i); //Just remove the sheets that don't match your criteria in the if statement above
}
FileOutputStream fos = new FileOutputStream(new File("D:\\DestinationFileName.xls"));
wb.write(fos);
fos.close();
System.out.println("file is copied in a new file at destination :"+"D:\\DestinationFileName.xls");
}
catch(Exception e){
e.printStackTrace();
}
聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.