![](https://i-blog.csdnimg.cn/blog_migrate/11ab61846568f7310c1fec6b75306fcd.jpeg)
全栈工程师开发手册 (作者:栾鹏)
java使用jxl包读写excel表格文件,即xls格式文件
本实例演示使用jxl包实现对excel文件的操作,下载
测试代码
public static void main(String[] arges){
ArrayList<ArrayList<String>> alldata=read_excel("myfile.xls");
write_excel("myfile1.xls",alldata);
}
写入xls文件代码
public static void write_excel(String filepath,ArrayList<ArrayList<String>> data){
try{
//创建一个可写入的excel文件对象
WritableWorkbook workbook = Workbook.createWorkbook(new File(filepath));
//使用第一张工作表
WritableSheet sheet = workbook.createSheet("工作表1", 0);
for (int i = 0; i < data.size(); i++) {
ArrayList<String> onerow=data.get(i);
for (int j = 0; j < onerow.size(); j++) {
String cell = onerow.get(j);
Label label=new Label(j,i,data.get(i).get(j));
sheet.addCell(label);
}
}
// //格式化日期
// jxl.write.DateFormat df = new jxl.write.DateFormat("yyyy-dd-MM hh:mm:ss");
// jxl.write.WritableCellFormat wcfDF = new jxl.write.WritableCellFormat(df);
// jxl.write.DateTime labelDTF = new jxl.write.DateTime(0, 1, new java.util.Date(), wcfDF);
// sheet.addCell(labelDTF);
//
// //格式化数字
// jxl.write.NumberFormat nf = new jxl.write.NumberFormat("#.##");
// WritableCellFormat wcfN = new WritableCellFormat(nf);
// jxl.write.Number labelNF = new jxl.write.Number(2, 1, 13.1415926, wcfN);
// sheet.addCell(labelNF);
//
//关闭对象,释放资源
workbook.write();
workbook.close();
}catch(Exception e){
System.out.println(e);
}
}
读取xls文件代码
public static ArrayList<ArrayList<String>> read_excel(String filepath) {
ArrayList<ArrayList<String>> alldata=new ArrayList<ArrayList<String>>();
Workbook workbook=null;
try {
workbook=Workbook.getWorkbook(new File(filepath));
Sheet sheet=workbook.getSheet(0); //使用第一个工作表
int row=sheet.getRows();
int column=sheet.getColumns();
for (int i = 0; i < row; i++) {
ArrayList<String> onerow=new ArrayList<String>();
for (int j = 0; j < column; j++) {
Cell a2=sheet.getCell(j, i);
String rest=a2.getContents();
if(rest!=null)
onerow.add(rest);
}
alldata.add(onerow);
}
} catch (Exception e) {
e.printStackTrace();
if (workbook!=null) {
workbook.close();
}
}
return alldata;
}