摘要:讀ops需要jopendocument的jar,讀xls需要apache.poi的jar
import java.io.File;
import java.io.FileInputStream;
import java.io.IOException;
import java.io.InputStream;
import org.apache.poi.hssf.usermodel.HSSFCell;
import org.apache.poi.hssf.usermodel.HSSFRow;
import org.apache.poi.hssf.usermodel.HSSFSheet;
import org.apache.poi.hssf.usermodel.HSSFWorkbook;
import org.jopendocument.dom.spreadsheet.MutableCell;
import org.jopendocument.dom.spreadsheet.Sheet;
import org.jopendocument.dom.spreadsheet.SpreadSheet;
public class readFile {
public static void main(String[] args) throws IOException {
// TODO Auto-generated method stub
// MultipartFile file = (MultipartFile) new File("C:\\Users\\rickeysu\\Desktop\\140.ods");
File file = new File("C:\\Users\\rickeysu\\Desktop\\140.xls");
String fileName = file.getName();
if (fileName.toUpperCase().endsWith("ODS")) {
System.out.println("is ODS");
// File convFile = new File(file.getOriginalFilename());
// convFile.createNewFile();
readODS(file);
} else if (fileName.toUpperCase().endsWith("XLS")) {
System.out.println("is XLS");
readXLS(file);
}
}
public static void readODS(File file)
{
Sheet sheet;
try {
//Getting the 0th sheet for manipulation| pass sheet name as string
sheet = SpreadSheet.createFromFile(file).getSheet(0);
//Get row count and column count
int nColCount = sheet.getColumnCount();
int nRowCount = sheet.getRowCount();
System.out.println("Rows :"+nRowCount);
System.out.println("Cols :"+nColCount);
//Iterating through each row of the selected sheet
MutableCell cell = null;
for(int nRowIndex = 0; nRowIndex < nRowCount; nRowIndex++)
{
//Iterating through each column
int nColIndex = 0;
for( ;nColIndex < nColCount; nColIndex++)
{
cell = sheet.getCellAt(nColIndex, nRowIndex);
System.out.print(cell.getValue()+ " ");
}
System.out.println();
}
} catch (IOException e) {
e.printStackTrace();
}
}
public static void readXLS(File file) {
InputStream fin = null;
try {
// fin = file.getInputStream(); //MultipartFile
fin = new FileInputStream(file);
HSSFWorkbook wb = new HSSFWorkbook(fin);
HSSFSheet sheet = wb.getSheetAt(0);
String result = "";
HSSFCell cell;
String[] a = null;
String tmpRow = "";
int i = 1;
while (i < sheet.getPhysicalNumberOfRows()) {
a = new String[11];
HSSFRow row = sheet.getRow(i);
for (int j = 0; j <= 11; j++) {
// row.getPhysicalNumberOfCells()
cell = row.getCell(j);
if (cell == null) {
result = "";
} else {
int ctype = cell.getCellType();
if (ctype == HSSFCell.CELL_TYPE_STRING) {
System.out.println("value=====" + cell.getRichStringCellValue().getString());
}
}
}
i++;
}
} catch (IOException e) {
// TODO Auto-generated catch block
throw new RuntimeException(e);
}
}
}