java 中使用jxl读取excel中的数据以及向excel中写入数据

1:读取excel中的数据

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.HashMap;
import java.util.List;
import java.util.Map;

import jxl.Cell;
import jxl.Sheet;
import jxl.Workbook;
import jxl.read.biff.BiffException;

public class ReadExcel {

public static void main(String[] args) {
try {
InputStream fis =new FileInputStream(new File("D:\\readExcel.xls"));
Workbook wb=Workbook.getWorkbook(fis);

Sheet sheet=wb.getSheet(0);


Cell cell=sheet.getCell(0, 0);

System.out.println(cell.getContents());


Map<Integer,List>map=new HashMap<Integer,List>();

for (int i = 0; i < sheet.getRows(); i++) {

List list =new ArrayList();
for (int j = 0; j < sheet.getColumns(); j++) {
cell=sheet.getCell(j, i);

String content=cell.getContents();

list.add(content);
}

map.put(i+1, list);
}


for (Integer i : map.keySet()) {
for (int j = 0; j < map.get(i).size(); j++) {
System.out.print(map.get(i).get(j));
}
System.out.println();
}


} catch (FileNotFoundException e) {
// TODO Auto-generated catch block
e.printStackTrace();
} catch (BiffException e) {
// TODO Auto-generated catch block
e.printStackTrace();
} catch (IOException e) {
// TODO Auto-generated catch block
e.printStackTrace();
}

}
}

 

2:向excel中写入数据(数据临时编的,数据集合应该来源于数据库)

import java.io.File;
import java.io.IOException;
import java.util.ArrayList;
import java.util.List;

import com.entity.User;

import jxl.Workbook;
import jxl.write.Label;
import jxl.write.WritableSheet;
import jxl.write.WritableWorkbook;
import jxl.write.WriteException;
import jxl.write.biff.RowsExceededException;

public class WriteExcel {

public static void main(String[] args) {
List<User>list=new ArrayList<User>();
User user=null;

for (int i = 0; i < 5; i++) {
user=new User(i+1, "阿伦"+i, "男"+i, 11+i, "2"+i);
list.add(user);
}


try {
WritableWorkbook wwb=Workbook.createWorkbook(new File("D:\\"+System.nanoTime()+".xls"));

WritableSheet ws=wwb.createSheet("user表", 0);
String[] titles={"编号","姓名","性别","年龄","年级"};
for (int i = 0; i < titles.length; i++) {
Label label=new Label(i,0,titles[i]);



ws.addCell(label);
}

for (int i = 0; i < list.size(); i++) {
user=list.get(i);

for (int j = 0; j < titles.length; j++) {
String content="";
if (j==0){
content=user.getUid().toString();
}else if(j==1){
content=user.getUname();
}else if(j==2){
content=user.getSex();
}else if(j==3){
content=user.getAge().toString();
}else if(j==4){
content=user.getGrade();
}
Label label=new Label(j,i+1,content);
ws.addCell(label);
}
}
wwb.write();
wwb.close();

} catch (IOException e) {

e.printStackTrace();
} catch (RowsExceededException e) {
// TODO Auto-generated catch block
e.printStackTrace();
} catch (WriteException e) {
// TODO Auto-generated catch block
e.printStackTrace();
}


}

}

posted @ 2018-04-23 14:48  性感的小辣椒  阅读(584)  评论(0编辑  收藏  举报