Last active
December 27, 2015 18:19
-
-
Save precious-ming/7368700 to your computer and use it in GitHub Desktop.
使用jxl创建、读取和修改excel。
This file contains hidden or bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
---导入jar包或者使用maven | |
maven | |
<dependency> | |
<groupId>net.sourceforge.jexcelapi</groupId> | |
<artifactId>jxl</artifactId> | |
<version>2.6.12</version> | |
</dependency> | |
1、生成excel | |
package com.puhui.util; | |
import java.io.File; | |
import jxl.Workbook; | |
import jxl.write.Label; | |
import jxl.write.WritableSheet; | |
import jxl.write.WritableWorkbook; | |
//生成excel的类 | |
public class CreateExcel { | |
public static void main(String args[]) { | |
try { | |
// 打开文件 | |
WritableWorkbook book = Workbook.createWorkbook(new File("D:/test.xls")); | |
// 生成名为“第一页”的工作表,参数0表示这是第一页 | |
WritableSheet sheet = book.createSheet("第一页 ",0); | |
// 在Label对象的构造子中指名单元格位置是第一列第一行(0,0) | |
// 以及单元格内容为test | |
Label label = new Label(0,0,"test"); | |
// 将定义好的单元格添加到工作表中 | |
sheet.addCell(label); | |
/* | |
* 生成一个保存数字的单元格 必须使用Number的完整包路径,否则有语法歧义 单元格位置是第二列,第一行,值为789.123 | |
*/ | |
jxl.write.Number number = new jxl.write.Number(1,0,555.12541); | |
sheet.addCell(number); | |
// 写入数据并关闭文件 | |
book.write(); | |
book.close(); | |
}catch (Exception e) { | |
System.out.println(e); | |
} | |
} | |
} | |
2、读取excel | |
package com.puhui.util; | |
// 读取Excel的类 | |
import java.io.File; | |
import jxl.Cell; | |
import jxl.Sheet; | |
import jxl.Workbook; | |
public class ReadExcel { | |
public static void main(String args[]) { | |
try { | |
Workbook book = Workbook.getWorkbook(new File("D:/test.xls")); | |
// 获得第一个工作表对象 | |
Sheet sheet = book.getSheet(0); | |
// 得到第一列第一行的单元格 | |
Cell cell1 = sheet.getCell(0,0); | |
String result = cell1.getContents(); | |
System.out.println(result); | |
book.close(); | |
} catch (Exception e) { | |
System.out.println(e); | |
} | |
} | |
} | |
3、修改excel | |
import java.io.File; | |
import jxl.Workbook; | |
import jxl.write.Label; | |
import jxl.write.WritableSheet; | |
import jxl.write.WritableWorkbook; | |
//修改excel | |
public class UpdateExcel { | |
public static void main(String args[]){ | |
try { | |
// Excel获得文件 | |
Workbook wb = Workbook.getWorkbook(new File("D:/test.xls")); | |
// 打开一个文件的副本,并且指定数据写回到原文件 | |
WritableWorkbook book = Workbook.createWorkbook(new File("D:/test.xls"),wb); | |
// 添加一个工作表 | |
WritableSheet sheet = book.createSheet("第二页 ",1); | |
sheet.addCell(new Label(0,0,"第二页的测试数据 ")); | |
book.write(); | |
book.close(); | |
} catch (Exception e) { | |
System.out.println(e); | |
} | |
} | |
} |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment