第一步 : 读入jxl-2.4.2.jar
第二步就是开发了
写Excel
public void WriteExcel() throws Exception{
File file = new File(“D:\excel.xls”);
OutputStream os = new FileOutputStream(file);
String[] title = {“编号”,”产品名称”,”产品价格”,”产品数量”,”生产日期”,”产地”,”是否出口”};
WritableWorkbook ww;
ww = Workbook.createWorkbook(os);//创建工作簿
WritableSheet sheet = ww.createSheet(“myExcel”, 0);//创建表格
/**
* 给表格中的内容设置样式
*/
CellFormat cf = ww.getSheet(0).getCell(1, 0).getCellFormat();
WritableCellFormat wc = new WritableCellFormat();
// 设置居中
wc.setAlignment(Alignment.CENTRE);
// 设置边框线
wc.setBorder(Border.ALL, BorderLineStyle.THIN);
// 设置单元格的背景颜色
wc.setBackground(jxl.format.Colour.RED);
Label label;
/**
* 设置指定单元格的宽度
* setColumnView(x,y) x代表第几列 y代表这一列的宽度
*/
sheet.setColumnView(0, 20);
sheet.setColumnView(1, 15);
sheet.setColumnView(2, 15);
sheet.setColumnView(3, 15);
sheet.setColumnView(4, 15);
sheet.setColumnView(5, 15);
sheet.setColumnView(6, 15);
for(int i=0;i<title.length;i++){
//Label(x,y,z) 代表单元格的第x+1列,第y+1行, 内容z
// 在Label对象的子对象中指明单元格的位置和内容
// label = new Label(i,0,title[i]);
label = new Label(i, 0, title[i], getHeader());//给i+1列 0+1行 的单元格添加title【i】内容 并指定getHeader()样式
// 将定义好的单元格添加到工作表中
sheet.addCell(label);
}
for(int i=0;i<9;i++){
sheet.addCell(new Label(0, i + 1, "teuyy", wc));
sheet.addCell(new Label(1, i + 1, "ofsyudgdh"));
sheet.addCell(new Label(2, i + 1, "sgj", wc));
sheet.addCell(new Label(3, i + 1, "tweourtuy", wc));
sheet.addCell(new Label(4, i + 1, "glj"));
sheet.addCell(new Label(5, i + 1, "twreyiu", wc));
sheet.addCell(new Label(6, i + 1, "cbhvcxzn"));
}
ww.write();
ww.close();
}
读Excel
public void ReadExcel() throws Exception{
File file = new File(“D:\excel.xls”);
InputStream Is = new FileInputStream(file);
Workbook ww = Workbook.getWorkbook(Is);
Sheet sheet = ww.getSheet(0);
List<String> list = new ArrayList<String>();
for(int i=0;i<sheet.getRows();i++){
String str="";
for(int j=0;j<sheet.getColumns();j++){
Cell cell = sheet.getCell(j, i);
str+=cell.getContents()+";";
}
list.add(str);
}
ww.close();
for(String lc:list){
System.out.println(lc);
}
}