代码示例:
package com.is.excel;
import java.io.File;
import java.io.FileOutputStream;
import jxl.Workbook;
import jxl.format.Alignment;
import jxl.format.Colour;
import jxl.format.UnderlineStyle;
import jxl.format.VerticalAlignment;
import jxl.write.Label;
import jxl.write.WritableCellFormat;
import jxl.write.WritableFont;
import jxl.write.WritableSheet;
import jxl.write.WritableWorkbook;
/*
* write data into a sheet of a excel
*/
public class ExportData {
public static boolean exportExcel(String strFileName, String strSheetName,
String strContent) {
WritableWorkbook wwb;
FileOutputStream fos;
try{
File f = new File(strFileName);
// if file not exist, create xls; else modify xls
if(f.exists() && f.length() > 0){
Workbook wb = Workbook.getWorkbook(f);
wwb = Workbook.createWorkbook(f, wb);
} else{
fos = new FileOutputStream(strFileName);
wwb = Workbook.createWorkbook(fos);
}
WritableSheet ws = wwb.getSheet(strSheetName);
// if sheet not exist, create sheet; else modify xls
if(ws == null){
ws = wwb.createSheet(strSheetName,wwb.getSheets().length);
} else{
ws.removeColumn(0);
for(int i=0; i<ws.getColumns(); i++){
ws.removeColumn(0);
}
}
WritableFont wf = new WritableFont(WritableFont.createFont("微软雅黑"), 10,
WritableFont.NO_BOLD, false, UnderlineStyle.NO_UNDERLINE,
Colour.BLACK);
WritableCellFormat wcf = new WritableCellFormat(wf);
wcf.setVerticalAlignment(VerticalAlignment.CENTRE);
wcf.setAlignment(Alignment.CENTRE);
wcf.setWrap(true);
// set first row height
ws.setRowView(0, 500);
String[] strAccountManage = strContent.split("\r\n");
String[] strField;
int i=0,j=0;
for(i=0; i<strAccountManage.length; i++){
strField = strAccountManage[i].split(",");
for(j=0; j<strField.length; j++){
strField[j] = strField[j].replaceAll("\"", "");
ws.addCell(new Label(j,i,strField[j],wcf));
}
}
for(i=0; i<j; i++){
// set column width
ws.setColumnView(i, 20);
}
wwb.write();
wwb.close();
return true;
} catch(Exception ex){
ex.printStackTrace();
return false;
}
}
}
注:涉及到文件的操作,建议慎重检查下代码安全性,尤其对于操作历史数据文件的情况。本人在应用上述代码的过程中就因为一个bug(sheet页不存在,未处理,导致文件写入失败),整个excel全被清空了,我积累了N久的历史数据就随之消失了(好在事发半月前拷贝了一个副本,不然。。。)。