Apache poi “如何修复”;提供的数据似乎位于Office 2007+;XML;
这是我从xlsx文件中提取值并在Eclipse控制台上打印的代码Apache poi “如何修复”;提供的数据似乎位于Office 2007+;XML;,apache-poi,Apache Poi,这是我从xlsx文件中提取值并在Eclipse控制台上打印的代码 public class testcode { public void readexcel(String filepath, String filename, String sheetname) throws IOException { //Create an object of file class to open xlsx file File file =
public class testcode {
public void readexcel(String filepath, String filename, String sheetname) throws IOException
{
//Create an object of file class to open xlsx file
File file = new File(filepath+"\\"+filename);
//Create an object of FileInputStream to read an xlsx file
FileInputStream inputstream = new FileInputStream(file);
Workbook workbook = null;
//Find file extension name by using substring
String FileExtensionName = filename.substring(filename.indexOf("."));
//Check condition whether file is xlsx or xls
if(FileExtensionName.equalsIgnoreCase("xlsx"))
workbook = new XSSFWorkbook(inputstream);
else
workbook = new HSSFWorkbook(inputstream);
//Read sheet inside the workbook by its name
Sheet sheet = workbook.getSheet(sheetname);
//Find number of rows in sheet
int rowCount = sheet.getLastRowNum() - sheet.getFirstRowNum();
//Create a loop over all the rows of excel file to read it
for(int i = 0; i<rowCount+1;i++)
{
Row row = sheet.getRow(i);
//Create loop to print cell values in a row
for(int j = 0; j<row.getLastCellNum();j++)
{
//Print excel value in console System.out.println(row.getCell(j).getStringCellValue()+"||");
}
System.out.println();
}
}
public static void main(String[] args) throws IOException {
testcode objExcelFile = new testcode();
//Prepare path of excel file
String filepath = "C:\\Users\\malfoy\\Desktop";
objExcelFile.readexcel(filepath,"testfile.xlsx", "read");
}
}
公共类测试代码{
public void readexcel(字符串文件路径、字符串文件名、字符串表名)引发IOException
{
//创建file类的对象以打开xlsx文件
文件文件=新文件(文件路径+“\\”+文件名);
//创建FileInputStream对象以读取xlsx文件
FileInputStream inputstream=新的FileInputStream(文件);
工作簿=空;
//使用子字符串查找文件扩展名
字符串FileExtensionName=filename.substring(filename.indexOf(“.”);
//检查文件是xlsx还是xls的条件
if(FileExtensionName.equalsIgnoreCase(“xlsx”))
工作簿=新XSSF工作簿(inputstream);
其他的
工作簿=新的HSSF工作簿(inputstream);
//按工作表的名称阅读工作表
Sheet Sheet=工作簿.getSheet(sheetname);
//查找工作表中的行数
int rowCount=sheet.getLastRowNum()-sheet.getFirstRowNum();
//在excel文件的所有行上创建一个循环以读取它
对于(inti=0;i
String FileExtensionName = filename.substring(filename.indexOf("."));
返回带点的值(在“.xlsx”的情况下)
因此,下面的if语句返回一个HSSFWorkbook实例,而不是XSSF工作簿
要更正它,请使用
String FileExtensionName = filename.substring(filename.lastIndexOf(".")+1);
为什么不直接使用WorkbookFactory
自动检测类型并为您选择合适的类型?