Apache POI使用许多工作表读取excel文件并将单页写入新文件

时间:2014-05-22 18:29:50

标签: java excel apache-poi

我正在使用Apache POI来读取包含许多工作表的xlsx文件。 我想将内容写入新的xlsx文件,但我只想从原始输入中选择一个工作表。

我的示例(下面的代码)读取文件正常,但它会将所有工作表写入文件。我需要知道如何只写一张纸。 我能这样做吗?

import java.io.*;
import org.apache.poi.xssf.usermodel.XSSFWorkbook;

public class ExcelTest {

    public static void main(String[] args)
    {  

    try
    {
        FileInputStream file = new FileInputStream(new File("FileLotOfSheets.xlsx"));
        //Create Workbook instance holding reference to .xlsx file
        XSSFWorkbook workbook = new XSSFWorkbook(file);

        //Get first/desired sheet from the workbook
       // XSSFSheet sheet = workbook.getSheetAt(0);

        file.close();

        FileOutputStream out = new FileOutputStream("FileOnlyOneSheetFromLots.xlsx");
        workbook.write(out);
        out.close();
    }
    catch (Exception e)
    {
        e.printStackTrace();
    }

    }
}

2 个答案:

答案 0 :(得分:0)

public static void main(String[] args) {
    // TODO Auto-generated method stub
    try {
        FileInputStream file = new FileInputStream(new File(
                "FileLotOfSheets.xlsx"));
        // Create Workbook instance holding reference to .xlsx file
        XSSFWorkbook workbook = new XSSFWorkbook(file);

        /* ------------------------------------------------------------ 
         * As per suggestion from rgettman to remove all but desired sheet,
         * added the following lines to get rid of the unwanted sheets.
         * Result is workbook with only the sheet I want.
         * ------------------------------------------------------------- */
        String sheetName = "mySheet";
        for (int i = workbook.getNumberOfSheets() - 1; i >= 0; i--) {
            XSSFSheet tmpSheet = workbook.getSheetAt(i);
            if (!tmpSheet.getSheetName().equals(sheetName)) {
                workbook.removeSheetAt(i);
            }
        }
        /*----------------------------------------------------------------*/

        file.close();

        FileOutputStream out = new FileOutputStream(
                "FileOnlyOneSheetFromLots.xlsx");
        workbook.write(out);
        out.close();
    } catch (Exception e) {
        e.printStackTrace();
    }
}

答案 1 :(得分:0)

考虑以下版本的main

 public static void main( String [] args ) {
  try {

    InputStream input = POIExample.class.getResourceAsStream( "qa.xls" );
    POIFSFileSystem fs = new POIFSFileSystem( input );
    HSSFWorkbook wb = new HSSFWorkbook(fs);


    for (int i = 0; i < wb.getNumberOfSheets(); i++) {
        HSSFSheet sheet = wb.getSheetAt(i);

        // Do your stuff        
    }

} catch ( IOException ex ) {
    ex.printStackTrace();
}
}