简体   繁体   English

用Apache POI读取数据时出现问题。 读取数据,但之后excel文件损坏

[英]Issue with reading data with apache POI. Data is read but excel file is corrupted afterwards

import java.io.File;
import java.io.FileInputStream;
import java.io.FileNotFoundException;
import java.io.FileOutputStream;
import java.io.IOException;

import org.apache.poi.ss.usermodel.Cell;
import org.apache.poi.xssf.usermodel.XSSFSheet;
import org.apache.poi.xssf.usermodel.XSSFWorkbook;

public class ExcelData {
    File fs;
    FileInputStream fis;
    XSSFWorkbook workbook;
    XSSFSheet sheet;
    FileOutputStream fos;

    public ExcelData(String datafile_path) throws Exception{

        fs=new File(datafile_path);
        fis=new FileInputStream(fs);
        workbook=new XSSFWorkbook(fis);
        fos=new FileOutputStream(fs);

public Object readData(int sheet_num, int row_num, int column_num) throws Exception{

        sheet=workbook.getSheetAt(sheet_num);
        //sheet.getRow(row_num).getCell(column_num).CELL_TYPE_STRING;
        Object data = null;
        if (sheet.getRow(row_num).getCell(column_num).getCellType()==Cell.CELL_TYPE_STRING){
            data=sheet.getRow(row_num).getCell(column_num).getStringCellValue();
        } else if (sheet.getRow(row_num).getCell(column_num).getCellType()==Cell.CELL_TYPE_NUMERIC){
            data=sheet.getRow(row_num).getCell(column_num).getNumericCellValue();
        }
        workbook.close();
        //String data=sheet.getRow(row_num).getCell(column_num).getStringCellValue();
workbook.close();
        fis.close();        
return data;

    }

----This code is working in reading the data. ----这段代码正在读取数据。 All the data is read successfully but after execution when look at the file, it is corrupted and size is 0 kb from 10 kb. 所有数据均已成功读取,但是在执行该命令后,在查看该文件时,该数据已损坏,并且大小为10 kb至0 kb。

Following snippet works for ".xls" file extension 以下片段适用于“ .xls”文件扩展名

public String[][] readFile(String filePath) throws IOException, BiffException {
    int totalNoOfRows, totalNoOfCols;

    FileInputStream fis = new FileInputStream(filePath);

    Workbook wb = Workbook.getWorkbook(fis);

    // To get the access to the sheet
    Sheet sh = wb.getSheet("Sheet1");

    // To get the number of rows present in sheet
    totalNoOfRows = sh.getRows();
    // To get the number of columns present in sheet
    totalNoOfCols = sh.getColumns();

    String[][] excelData = new String[totalNoOfRows][totalNoOfCols];

    for (int row = 0; row < totalNoOfRows; row++) {
        for (int col = 0; col < totalNoOfCols; col++) {
            excelData[row][col] = sh.getCell(col, row).getContents();
        }
    }

    wb.close();
    fis.close();
    return excelData;
}

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM