/**
*
* @param datas 數據行
* @param filePath 導出文件路徑
* @param title 標題
* @return
*/
public boolean ListArray2Excel(List<String[]> datas, String filePath,
String[] title) {
boolean flag = false;
WritableWorkbook workbook = null;
WritableSheet sheet = null;
Label label = null;
// 建立Excel表
try {
workbook = Workbook.createWorkbook(new File(filePath));
// 建立Excel表中的sheet
sheet = workbook.createSheet("seo_url", 0);
// 向Excel中添加數據
int row = 0;
// 添加標題
for (int i = 0; i < title.length; i++) {
label = new Label(i, row, title[i]);
sheet.addCell(label);
}
row++;
for (String[] data : datas) {
for (int i = 0; i < data.length; i++) {
for (int j = 0; j < title.length; j++) {
label = new Label(i, row, data[i]);
sheet.addCell(label);
}
}
row++;
}
// 關閉文件
workbook.write();
workbook.close();
workbook = null;
flag = true;
} catch (RowsExceededException e) {
} catch (WriteException e) {
} catch (IOException e) {
} finally {
try {
workbook.close();
} catch (Exception e) {
}
}
return flag;
}
測試:
/**
* 測試方法
*
* @param args
*/
public static void main(String[] args) {
//
List<String[]> data = new ArrayList<String[]>();
String[] strArray = { "銅", "http://www.baidu.com" };
String[] strArray2 = { "紫銅", "http://www.guge.com" };
data.add(strArray);
data.add(strArray2);
try {
String[] title = { "詞名", "url" };
if (!new ExcelUtil().ListArray2Excel(data,
"d:/test/" + System.currentTimeMillis() + ".xls", title)) {
System.out.println("數據寫入失敗");
}
} catch (Exception e) {
e.printStackTrace();
}
}