Java之excel文件的写入和读取
近期一直在做的事基本都是将各种类型的数据写入excel中,比如csv,xml,json等等,数据基本都十多万条,没什么技术含量但也是个麻烦活,实际开发中难免用到,所以有必要写一篇博客。
我用的jar是jxl.jar,Apache的poi也是个很好的选择,而且能够设置一些格式和风格,如果做的只是简单的数据写入和导出,前者就OK了。
只是有一点需要注意:jxl无法处理较高版本的excel,假如读取07版(或更高)的excel文件会报如下错误

解决方案为:将原文件另存为97-03版本的;如果不想改变版本,就使用poi来操作(博客最后附有poi的操作链接)
下面是jxl的相关操作:
比如有下面一个csv文件(一般以逗号为分隔符,这里用 | 做为分隔符):
100|winter|22|m 101|小明|21|f 102|小刚|23|m
创建一个User类
public class User{
private Integer ID; private String name; private Integer age; private Character sex; public Test() { // TODO Auto-generated constructor stub }
public Integer getID() { return ID; } public void setID(Integer iD) { ID = iD; } public String getName() { return name; } public void setName(String name) { this.name = name; } public Integer getAge() { return age; } public void setAge(Integer age) { this.age = age; } public Character getSex() { return sex; } public void setSex(Character sex) { this.sex = sex; } }
使用流读取csv文件,并赋值到User对象,返回List<User>
public static List<User> getUsers(String filePath){ BufferedReader br=null; List<Test> users=new ArrayList<>(); try { br=new BufferedReader(new FileReader(filePath)); String userInfo; while((userInfo=br.readLine())!=null){
//读取每一行后分割成字符串数组,温习提示,String的split(“\\|”)中参数要使用转义符‘\\’,不使用的话有些情况下会不好使。 String[] strs=userInfo.split("\\|"); User user=new User(); user.setID(Integer.valueOf(strs[0])); user.setName(strs[1]); user.setAge(Integer.valueOf(strs[2])); user.setSex(strs[3].charAt(0)=='f'?'女':'男'); users.add(user); } } catch (Exception e) { // TODO Auto-generated catch block e.printStackTrace(); }finally{ try { br.close(); } catch (IOException e) { // TODO Auto-generated catch block e.printStackTrace(); } } return users; }
那么接下就是重点了:将数据写入excel表
public static void writeToExcel(List<User> users){ WritableWorkbook wwb = null; try { int k=0; // 创建可写入的Excel工作簿,文件路径自定义 String fileName = "E://hb2.xls"; File file=new File(fileName); if (!file.exists()) { file.createNewFile(); } wwb = Workbook.createWorkbook(file); // 创建sheet,第一个参数是sheet的名称,第二个参数是页码(一次最多只能写入65535行数据,所以当要插入的数据大于65535时,定义一个变量num充当计数器, //if(num%65535==0)时再次创建一个sheet即可) WritableSheet ws = wwb.createSheet("winter", 0); //参数分别为列数,行数,内容,很有意思,前两个如同经纬度来让它确定一个唯一位置,第三个告诉它要插入的内容 Label labelId= new Label(0, 0, "用户ID"); Label labelName= new Label(1, 0, "名称"); Label labelAge= new Label(3, 0, "年龄"); Label labelSex= new Label(4, 0, "性别"); //将四个标签加入到sheet里 ws.addCell(labelId); ws.addCell(labelName); ws.addCell(labelAge); ws.addCell(labelSex); //这时候行数要从1开始计数了 int num=1; for(Test user:users){ Label labelId_i= new Label(0, num, user.getID()+""); Label labelName_i= new Label(1, num, user.getName()); Label labelAge_i= new Label(3, num, user.getAge()+""); Label labelSex_i= new Label(4, num, user.getSex()+""); ws.addCell(labelId_i); ws.addCell(labelName_i); ws.addCell(labelAge_i); ws.addCell(labelSex_i); num++; //if(num%65535==0) // ws=wwb.createSheet("xxx", n); } //把之前加进去的数据一次性写进excel文件里 wwb.write(); }catch(Exception e){ e.printStackTrace(); }finally{ try { wwb.close(); } catch (WriteException e) { // TODO Auto-generated catch block e.printStackTrace(); } catch (IOException e) { // TODO Auto-generated catch block e.printStackTrace(); } } }
写入就是这么多,接下来是读取:
public static List<User> readFromExcel(String filePath){ List<User> list=new ArrayList<User>(); try { Workbook wb=Workbook.getWorkbook(new File(filePath)); //根据name获取sheet Sheet s=wb.getSheet("winter"); int clos=s.getColumns();//得到所有的列 int rows=s.getRows();//得到所有的行 //接下来就是类似于遍历一个二维数组 for (int i = 1; i < rows; i++) { for (int j = 0; j < clos; j++) { //第一个是列数,第二个是行数
String id=s.getCell(j++, i).getContents(); String name=s.getCell(j++, i).getContents(); String age=rs.getCell(j++, i).getContents(); String sex=rs.getCell(j, i).getContents(); list.add(new User(Integer.parseInt(id), name, Integer.parseInt(num),sex.charAt(0))); } } } catch (Exception e) { // TODO Auto-generated catch block e.printStackTrace(); } return list; }
ok,简单操作就是这么多。poi的操作与此类似,感兴趣的可以看这个博客http://www.cnblogs.com/yjmyzz/p/POI-export-excel-sample.html

浙公网安备 33010602011771号