先看下結果圖:
代碼如下:
package com.excel;
import java.io.File;
import java.io.IOException;
import jxl.Workbook;
import jxl.write.Label;
import jxl.write.WritableSheet;
import jxl.write.WritableWorkbook;
import jxl.write.WriteException;
import jxl.write.biff.RowsExceededException;
public class ExcelWrite{
public static void writeExcel(String fileName){
WritableWorkbook wwb = null;
double Array[][] = new double[10][10];
for(int i = 0; i < 10; i ++){
for(int j = 0; j < 10; j ++){
Array[i][j] = Math.random()%10;
}
}
try {
//首先要使用Workbook類的工廠方法創建一個可寫入的工作薄(Workbook)對象
wwb = Workbook.createWorkbook(new File(fileName));
} catch (IOException e) {
e.printStackTrace();
}
if(wwb!=null){
//創建一個可寫入的工作表
//Workbook的createSheet方法有兩個參數,第一個是工作表的名稱,第二個是工作表在工作薄中的位置
WritableSheet ws = wwb.createSheet("工作表名稱", 0);
Label label0 = new Label(0,0,"詞項|主題");
try {
//將生成的單元格添加到工作表中
ws.addCell(label0);
} catch (RowsExceededException e) {
e.printStackTrace();
} catch (WriteException e) {
e.printStackTrace();
}
for(int i=1;i<=10;i++){
Label labelC = new Label(i, 0, "T"+i);
try {
//將生成的單元格添加到工作表中
ws.addCell(labelC);
} catch (RowsExceededException e) {
e.printStackTrace();
} catch (WriteException e) {
e.printStackTrace();
}
}
for(int j = 1; j <= 10; j ++){
Label labelC = new Label(0, j, "W"+j);
try {
//將生成的單元格添加到工作表中
ws.addCell(labelC);
} catch (RowsExceededException e) {
e.printStackTrace();
} catch (WriteException e) {
e.printStackTrace();
}
}
for(int j = 1; j <= 10; j ++){
for(int i = 1; i <= 10; i ++){
String str = Double.toString(Array[j-1][i-1]);
Label label = new Label(j, i , str);
try {
ws.addCell(label);
} catch (RowsExceededException e) {
// TODO Auto-generated catch block
e.printStackTrace();
} catch (WriteException e) {
// TODO Auto-generated catch block
e.printStackTrace();
}
}
}
try {
//從內存中寫入文件中
wwb.write();
//關閉資源,釋放內存
wwb.close();
} catch (IOException e) {
e.printStackTrace();
} catch (WriteException e) {
e.printStackTrace();
}
}
//循環對每一個單元格進行賦值
//定位行
}
public static void main(String[] args) {
String fileName = "E:\\IR1\\LDA迭代結果\\EXCEL結果保存\\test\\testt.xls";
ExcelWrite.writeExcel(fileName);
}
}
參考的文章和博客如下:
http://blog.csdn.net/mr_walter/article/details/8445905
http://hi.baidu.com/fbdfp/item/211402be43671d43bb0e123e
關於這個例子的程序包下載網址如下:
http://download.csdn.net/detail/a15994269853/7340965