java读写Excel文件

首先引入jxl.jar的第三方包。(在附件中)
示例代码:
public class ExcelTools {

/**
* 写Excel
*
* @param fileName
* 输出的Excel的文件名
* @param sheetName
* Excel工作表的名字
* @param title
* Excel工作表中每一列的标题
* @param list
* 存入表格的内容,每一条记录为一个String[],数组中的元素与title相对应
*/
public static void writeExcel(String fileName, String sheetName,
String[] title, List<String[]> list) {
WritableWorkbook workbook;
try {
OutputStream os = new FileOutputStream(fileName);
workbook = Workbook.createWorkbook(os);
WritableSheet sheet = workbook.createSheet(sheetName, 0); // 添加第一个工作表
jxl.write.Label label;
//添加每列的标题
for (int i = 0; i < title.length; i++) {
// Label(列号,行号 ,内容 )excel坐标原点是(0,0)
label = new jxl.write.Label(i, 0, title[i]);
sheet.addCell(label);
}
if (list != null) {
for (int i = 0; i < list.size(); i++) {
String[] tt = list.get(i);
for (int z = 0; z < tt.length; z++) {
// Label(列号,行号 ,内容 )excel坐标原点是(0,0)
label = new jxl.write.Label(z, i + 1, tt[z]);
sheet.addCell(label);
}
}
}
workbook.write();
workbook.close();
os.close();
} catch (Exception e) {
e.printStackTrace();
}
}

/**
* 读Excel
*
* @param fileName
* 文件名
* @param sheetNum
* 工作表的下标
* @return List<String[]>
* 集合中的一个元素为Excel表格中的一条记录
*/
public static List<String[]> readExcel(String fileName, int sheetNum) {
File file = new File(fileName);
InputStream is = null;
Workbook rwb = null;
Sheet stFile = null;
List<String[]> list = new ArrayList<String[]>();
if (file.exists() && file.length() > 0) {
try {
is = new FileInputStream(file);
rwb = Workbook.getWorkbook(is);
stFile = rwb.getSheet(sheetNum);
int cols = stFile.getColumns();
for (int r = 0; r < stFile.getRows(); r++) {
String[] record = new String[cols];
for (int c = 0; c < cols; c++) {
record[c] = stFile.getCell(c, r).getContents().trim();
}
list.add(record);
}
} catch (BiffException ex) {
ex.printStackTrace();
} catch (IOException ex) {
ex.printStackTrace();
} finally {
rwb.close();
if (is != null) {
try {
is.close();
} catch (IOException e) {
e.printStackTrace();
}
}
}
}
return list;
}
}
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值