JAVA编码与Excel的交互在实际开发中用的非常多,今天就简单用jxl实现二者的交互。废话不多说,直接贴码!
首先,得导入jxl架包:
1.将数据写入EXCEL中
package com.easyteam.yc01; import java.io.File; import jxl.Workbook; import jxl.write.Label; import jxl.write.WritableSheet; import jxl.write.WritableWorkbook; public class OperateExcel { public void getExcel() throws Exception{ File file = new File("d:"+File.separator+"a.xls");//创建文件 if(!file.exists()){ file.createNewFile(); } WritableWorkbook workBook=Workbook.createWorkbook(file);//创建工作薄 WritableSheet sheet=workBook.createSheet("sheet1",0);//创建Sheet String[] title={"id","name","age"};//定义表头元素 //将数据填充到 EXCEL中 for(int i=0;i<title.length;i++){ Label lable1=new Label(i,0,title[i]);//表头 Label lable2=new Label(0,i+1,i+"");//id Label lable3=new Label(1,i+1,"张三"+i);//name Label lable4=new Label(2,i+1,"100"+i);//age sheet.addCell(lable1); sheet.addCell(lable2); sheet.addCell(lable3); sheet.addCell(lable4); } workBook.write();//写入数据 workBook.close();//关闭 } }
测试:
package com.easyteam.yc01; public class Test { public static void main(String[] args) throws Exception { OperateExcel op=new OperateExcel(); op.getExcel(); } }
测试结果:
2.将EXCEL中的数据读取出来
package com.easyteam.yc01; import java.io.File; import java.io.IOException; import jxl.Cell; import jxl.Sheet; import jxl.Workbook; import jxl.read.biff.BiffException; import jxl.write.WritableWorkbook; public class GetExcelData { public void getData() throws Exception{ File file = new File("d:"+File.separator+"a.xls"); Workbook workBook=Workbook.getWorkbook(file);//得到工作薄 Sheet sheet =workBook.getSheet(0);//得到sheet int rows = sheet.getRows(); //行数 int columns = sheet.getColumns();//列数 for(int i=0;i<rows;i++){ for(int j=0;j<columns;j++){ Cell cell= sheet.getCell(j, i);//获取单元格 String str=cell.getContents();//获取单元格内容 System.out.print(str+"\t"); } System.out.println(); } } }
测试:
package com.easyteam.yc01; public class Test1 { public static void main(String[] args) throws Exception { GetExcelData ged=new GetExcelData(); ged.getData(); } }
测试结果:
时间: 2024-11-10 11:29:21