[英]Apache POI to read excel file with many worksheets and write single sheet to new file
我正在使用 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();
}
}
}
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();
}
}
考慮以下版本的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();
}
}
聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.