2009-05-11 44 views
21

Có ai biết phương tiện sao chép trang tính từ sổ làm việc này sang sổ làm việc khác bằng POI không? Lớp Workbook có một phương thức cloneSheet, nhưng dường như không thể chèn một bảng nhân bản vào một sổ làm việc mới?Sao chép Bảng tính Excel trong POI

Nếu không có API để thực hiện việc này dễ dàng, có ai có mã để sao chép tất cả dữ liệu (kiểu, độ rộng cột, dữ liệu, v.v ...) từ trang tính này sang trang tính khác không?

jxls có phương pháp sao chép trang tính nhưng chúng không hoạt động khi sao chép giữa các sổ làm việc.

+1

[Link] này (http://www.coderanch.com/t/420958/open-source/Copying-sheet-excel-file-another) sẽ hữu ích: – hkansal

+0

@hkansal liên kết mà tôi tìm thấy khi tôi đang googling. Tôi phải đối mặt với một vấn đề với mã được đưa ra trong liên kết đó, khi ô được nhóm theo nhóm khôn ngoan như A1: A4, nó hiển thị lỗi giống như vùng trùng nhau chồng chéo, tôi không thể đăng trả lời trong liên kết đó. Nó thực sự tốt. –

Trả lời

2

Nếu bạn đang sử dụng thư viện Java POI thì tốt nhất là tải Bảng tính vào bộ nhớ ,,, sau đó tạo bảng tính mới và viết từng bản ghi bạn muốn sao chép. không phải là cách tốt nhất nhưng hoàn thành chức năng sao chép ...

1

Tôi dành khoảng một tuần nỗ lực để thực hiện việc này với POI (sử dụng mã mới nhất trên coderanch) - được cảnh báo rằng mã không hoàn thiện (có vấn đề với bằng cách sử dụng TreeSet nơi bạn cần thay thế bằng HashMap), nhưng ngay cả sau khi sửa chữa nó bị treo trên các công thức.

Mặc dù có thể thực hiện một đề xuất đáng sợ là phải dựa vào mã bị tấn công.

Tùy thuộc vào nhu cầu của bạn/ngân sách mà bạn có thể muốn xem xét cắn đạn và trả tiền cho Aspose - http://www.aspose.com/doctest/java-components/aspose.cells-for-java/copy-move-worksheets-within-and-between-workbooks.html

Nó tờ sao chép thành công bao gồm định dạng, công thức, quy tắc bảo vệ &. Tôi đã làm 300 tờ trong 130 giây. (Sách bài tập 300 x 90kb, được biên soạn thành một sổ làm việc 15mb). Bản demo miễn phí, nó chỉ đặt thêm một tờ vào sổ làm việc nhắc bạn mua giấy phép.

5

tôi đã triển khai một số chức năng với poi. vui lòng xem mã để bạn tham khảo.

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(); 
    } 
} 
0

Đây là việc triển khai sao chép trang tính từ sổ làm việc này sang sổ làm việc khác. Giải pháp này làm việc cho tôi. Mã này sẽ hoạt động nếu các trang tính không có bảng, vv Nếu các trang tính chứa văn bản đơn giản (String, boolean, int, v.v.), các công thức, giải pháp này sẽ hoạt động.

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(); 

Nếu yêu cầu của bạn là sao chép toàn bộ trang tính mà không cần thoát hoặc thêm bất kỳ thứ gì. Tôi nghĩ rằng quá trình loại bỏ hoạt động tốt hơn và nhanh hơn sau đó mã trên. Và bạn không phải lo lắng về việc mất công thức, bản vẽ, bảng, kiểu, phông chữ, v.v.

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(); 
Các vấn đề liên quan