2017-01-08 11 views
0
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から0 kbです。apache POIでデータを読み取る際の問題。データは読み込まれますが、その後Excelファイルが破損します

+2

のために動作します。彼らはハムとハンバーガーと密接に関連しています – charlietfl

+2

ファイルの 'FileOutputStream'をなぜ開くのですか? 'Workbook.close'はその出力ストリームを閉じますが、何も書き込まれません。そのファイルは空です。何かを書きたいと思っていなければ、出力ストリームを開くべきではありません。 –

答えて

0

次のスニペットは、これは、Java、JavaScriptのではないです ".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; 
} 
+0

'Workbook.getWorkbook'は**ではありません**' apache poi'です。それは 'jxl'です。したがって、このコードはこの質問には関係ありません。 –

関連する問題