jxl读取excel
- 格式:docx
- 大小:26.70 KB
- 文档页数:11
Java Excel是一开放源码项目,通过它开发人员可以读取Excel文件的内容、创建新的Excel文件、更新已经存在的Excel文件以及插入图片等等。
ps:读取结束时注意调用close()方法;释放内存
写入结束时先调用write()方法,否则得到的是空Excel,因为先前的操作都是存储在缓存中。具体见代码
一、读取Excel的例子:
注意对数字、日期等不同CellType的读取
Java代码
/**
* jxl 读取
* @author Michael sun
*/
public class JxlRead {
/**
* 读取 excel 文件
* @param filePath
* @throws Exception
*/
private void readExcel(String filePath) throws Exception {
InputStream is = null;
Workbook workbook = null;
try {
is = new FileInputStream(filePath);
workbook = Workbook.getWorkbook(is);
// sheet row column 下标都是从0开始的
Sheet sheet = workbook.getSheet(0);
int column = sheet.getColumns();
int row = sheet.getRows();
System.out.println("共有" + row + "行," + column + "列数据");
// A1是字符
Cell cellA1 = sheet.getCell(0, 0);
System.out.println("A1 type:" + cellA1.getType());
if (cellA1.getType().equals(BEL)) {
System.out.println("A1 content:" +
cellA1.getContents());
}
// B1是数字
Cell cellB1 = sheet.getCell(1, 0);
System.out.println("B1 type:" + cellB1.getType()); if (cellB1.getType().equals(CellType.NUMBER)) {
NumberCell numberCell = (NumberCell) cellB1; double douval = numberCell.getValue();
System.out.println("B1 value:" + douval);
}
// C1是日期
Cell cellC1 = sheet.getCell(2, 0);
System.out.println("C1 type:" + cellC1.getType()); if (cellC1.getType().equals(CellType.DATE)) {
DateCell dateCell = (DateCell) cellC1;
Date date = dateCell.getDate();
System.out.println("C1 date:" + date);
}
// 操作完成时,关闭对象,释放占用的内存空间
workbook.close();
is.close();
} catch (Exception e) {
e.printStackTrace(System.out);
} finally {
if (is != null) {
is.close();
}
}
}
/**
* @param args
* @throws Exception
*/
public static void main(String[] args) throws Exception { String filePath = "D:\\test\\testjxlread.xls";
JxlRead jxlRead = new JxlRead();
jxlRead.readExcel(filePath);
}
二、写入Excel的例子:
Java代码
/**
* 写入excel
* @author Michael sun
*/
public class JxlWrite {
/**
* 写入 excel 文件
* @param filePath
* @throws Exception
*/
private void writeExcel(String filePath) throws Exception {
OutputStream os = null;
try {
// 构建Workbook对象
os = new FileOutputStream(filePath);
WritableWorkbook wwb = Workbook.createWorkbook(os);
// 构建Excel sheet
WritableSheet sheet = wwb.createSheet("test write sheet", 0);
// 设置标题格式
WritableFont wfTitle = new jxl.write.WritableFont(