Excel文件操作(jxl)

操作配置
<dependency>
<groupId>net.sourceforge.jexcelapi</groupId>
<artifactId>jxl</artifactId>
<version>2.6.10</version>
</dependency>

1、读取Excel文件
public void inputExcel(String filePath) {
InputStream is = null;
try {
is = new FileInputStream(new File(filePath));
} catch (FileNotFoundException e2) {
e2.printStackTrace();
}
Workbook workbook = null;
try {
workbook = Workbook.getWorkbook(is);
} catch (BiffException e1) {
e1.printStackTrace();
} catch (IOException e1) {
e1.printStackTrace();
}
int sheetNum = workbook.getNumberOfSheets();
for (int numSheets = 0; numSheets < sheetNum; numSheets++) {
if (null != workbook.getSheet(numSheets)) {
Sheet sheet = workbook.getSheet(numSheets);
int row = sheet.getRows();
for (int i = 1; i < row; i++) {
System.out.println(sheet.getCell(cell++, i).getContents());
}
}
}
}

2、生成Excel文件
public void outputExcel(String path, String tablename, List list) {
WritableWorkbook wb = null;
try {
wb = jxl.Workbook.createWorkbook(new File(path));
} catch (IOException e) {
e.printStackTrace();
}
if (wb != null) {
// 第一个参数表示工作表名称,第二个参数表示工作表所在工作薄的位置
jxl.write.WritableSheet ws = wb.createSheet(tablename, 0);
if (list.size() >= 1) {
try {
ws.addCell(new Label(0, 0, "cell1"));
ws.addCell(new Label(1, 0, "cell2"));
ws.addCell(new Label(2, 0, "cell3"));
ws.addCell(new Label(3, 0, "cell4"));
ws.addCell(new Label(4, 0, "cell5"));
} catch (WriteException e) {
e.printStackTrace();
}
Iterator itr = list.iterator();
int row = 1;
while (itr.hasNext()) {
Object obj = itr.next();
try {
ws.addCell(new Label(0, row, obj.get[1]));
ws.addCell(new Label(1, row, obj.get[2]));
ws.addCell(new Label(2, row, obj.get[3]));
ws.addCell(new Label(3, row, obj.get[4]));
ws.addCell(new Label(4, row, obj.get[5]));
} catch (WriteException e) {
e.printStackTrace();
}
row++;
}
}
try {
wb.write();
} catch (IOException e) {
e.printStackTrace();
}
try {
wb.close();
} catch (WriteException e) {
} catch (IOException e) {
}
}
}
  • 0
    点赞
  • 0
    收藏
    觉得还不错? 一键收藏
  • 0
    评论
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值