使用apache POI读取数据的问题。读取数据但之后excel文件已损坏

时间:2017-01-08 22:23:48

标签: java apache-poi

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;

    }

----此代码正在读取数据。所有数据都被成功读取但在执行后查看文件时,它已损坏,大小为10 kb,距离为10 kb。

1 个答案:

答案 0 :(得分:0)

以下代码段适用于" .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;
}