参考代码及注释如下:
import Java.io.Fileimport java.io.FileInputStreamimport java.io.FileNotFoundExceptionimport java.io.IOExceptionimport java.io.InputStream import org.apache.poi.hssf.usermodel.HSSFWorkbookimport org.apache.poi.ss.usermodel.Cellimport org.apache.poi.ss.usermodel.Rowimport org.apache.poi.ss.usermodel.Sheetimport org.apache.poi.ss.usermodel.Workbookpublic class ReadExcel { public static void readExcel(File file){ try { InputStream inputStream = new FileInputStream(file) String fileName = file.getName() Workbook wb = null// poi-3.9.jar 只可以读取2007以下的版本,后缀为:xsl wb = new HSSFWorkbook(inputStream)//解析xls格式 Sheet sheet = wb.getSheetAt(0)//第一个工作表 ,第二个则为1,以此类推... int firstRowIndex = sheet.getFirstRowNum() int lastRowIndex = sheet.getLastRowNum() for(int rIndex = firstRowIndexrIndex <= lastRowIndexrIndex ++){ Row row = sheet.getRow(rIndex) if(row != null){ int firstCellIndex = row.getFirstCellNum()// int lastCellIndex = row.getLastCellNum() //此处参数cIndex决定可以取到excel的列数。 for(int cIndex = firstCellIndexcIndex <3cIndex ++){ Cell cell = row.getCell(cIndex) String value = "" if(cell != null){ value = cell.toString() System.out.print(value+"\t") } } System.out.println() } } } catch (FileNotFoundException e) { // TODO 自动生成 catch 块 e.printStackTrace() } catch (IOException e) { // TODO 自动生成 catch 块 e.printStackTrace() } } public static void main(String[] args) { File file = new File("D:/test.xls") readExcel(file)}}
在java程序添加spire.xls.jar依赖
import com.spire.xls.*public class ReadExcel {
public static void main(String[] args) {
//创建Workbook对象
Workbook wb = new Workbook()
//加载一个Excel文档
wb.loadFromFile("C:\\Users\\Administrator\\Desktop\\test.xlsx")
//获取第一个工作表
Worksheet sheet = wb.getWorksheets().get(0)
//遍历工作表的每一行
for (int i = 1 i < sheet.getLastRow() + 1 i++) {
//遍历工作的每一列
for (int j = 1 j < sheet.getLastColumn() + 1 j++) {
//输出指定单元格的数据
System.out.print(sheet.get(i,j).getText())
System.out.print("\t")
}
System.out.print("\n")
}
}
}
欢迎分享,转载请注明来源:内存溢出
评论列表(0条)