前不久需要将excel 的数据导入到数据库里面去, 在网上找了几个示例,简单粗糙的写了下面这个 读取excel内容的 例子。日后使用时在继续完善。
package com.jerry;
import java.io.File;
import java.io.FileInputStream;
import java.io.FileNotFoundException;
import java.io.IOException;
import java.io.InputStream;
import java.util.ArrayList;
import java.util.List;
import jxl.Sheet;
import jxl.Workbook;
import jxl.read.biff.BiffException;
/**
* 读取表格内容
*
* @author yulisao
* @createDate 2019-2-16
*/
public class ReadExcel {
public static void main(String[] args) {
ReadExcel obj = new ReadExcel();
File file = new File("D:/source.xls");
List excelList = obj.readExcel(file);
System.out.println("Excel的内容如下: ");
for (int i = 0; i < excelList.size(); i++) {
List list = (List) excelList.get(i);
for (int j = 0; j < list.size(); j++) {
System.out.print(list.get(j) + "\t");
//dosomething example save to database
}
//打印完第一行元素换行
System.out.println();
}
}
// 去读Excel的方法readExcel,该方法的入口参数为一个File对象
public List readExcel(File file) {
try {
// 创建输入流,读取Excel
InputStream is = new FileInputStream(file.getAbsolutePath());
// jxl提供的Workbook类
Workbook wb = Workbook.getWorkbook(is);
// Excel的页签数
int sheet_size = wb.getNumberOfSheets();
for (int index = 0; index < sheet_size; index++) {
List<List> outerList=new ArrayList<List>();
// 每个页签创建一个Sheet对象
Sheet sheet = wb.getSheet(index);
// sheet.getRows()返回该页的总行数
for (int i = 0; i < sheet.getRows(); i++) {
List innerList=new ArrayList();
// sheet.getColumns()返回该页的总列数
for (int j = 0; j < sheet.getColumns(); j++) {
String cellinfo = sheet.getCell(j, i).getContents();
if(cellinfo.isEmpty()){
continue;
}
innerList.add(cellinfo);
//System.out.print(cellinfo);
}
outerList.add(i, innerList);
System.out.println();
}
return outerList;
}
} catch (FileNotFoundException e) {
e.printStackTrace();
} catch (BiffException e) {
e.printStackTrace();
} catch (IOException e) {
e.printStackTrace();
}
return null;
}
}