programing

POI에서 Excel 워크시트 복사

jooyons 2023. 4. 20. 21:12
반응형

POI에서 Excel 워크시트 복사

POI를 사용하여 워크북 간에 워크시트를 복사할 수 있는 방법을 아는 사람이 있습니까?워크북 클래스에 복제본이 있습니다.시트 방법. 그러나 복제된 시트를 새 워크북에 삽입할 수 없는 것 같습니다.

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에서 구현됩니다.NPOI 2.0은 https://npoi.codeplex.com/releases/view/112932 에서 다운로드할 수 있습니다.

이것은 워크북을 다른 워크북으로 복사하는 나의 실장입니다.이 솔루션은 나에게 효과가 있다.이 코드는 시트에 테이블 등이 없는 경우 작동합니다.시트에 단순한 텍스트(String, boolean, int 등), 수식이 포함되어 있는 경우, 이 솔루션은 기능합니다.

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

Java POI 라이브러리를 사용하는 경우 스프레드시트를 메모리에 로드하고 새 스프레드시트를 생성하여 복사할 레코드를 각각 쓰는 것이 가장 좋습니다.최선의 방법은 아니지만 복사 기능을 보완합니다.

POI(코더랜치의 최신 코드 사용)를 사용하기 위해 1주일 정도 노력했습니다.코드에 결함이 있다는 것을 주의해 주십시오(Tree Set을 HashMap으로 대체할 필요가 있는 경우 TreeSet 사용에는 문제가 있습니다).그러나 수식을 수정한 후에도 문제가 발생합니다.

해킹된 코드에 의존해야 하는 것은 가능할지 모르지만 무서운 제안입니다.

고객의 요구나 예산에 따라서는, 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();
    }

이 방법은 다음 사항을 명확히 하는 데 도움이 될 것입니다.

언급URL : https://stackoverflow.com/questions/848212/copying-excel-worksheets-in-poi

반응형