package com.dm.test.export;
import java.io.File;
import java.io.IOException;
import jxl.format.Border;
import jxl.format.BorderLineStyle;
import jxl.format.VerticalAlignment;
import jxl.read.biff.BiffException;
import jxl.write.NumberFormat;
import jxl.write.WritableCellFormat;
import jxl.write.WriteException;
import jxl.write.biff.RowsExceededException;
public class ExportExcel {
public void exportExcel() throws BiffException,IOException,
RowsExceededException,WriteException {
// 新创建的FILE的名字
String fileName ="d:\template.xls";
File file = newFile(fileName);
// 创建新的可写的EXCEL工作薄对象
jxl.write.WritableWorkbook wwb= jxl.Workbook.createWorkbook(file);
// 取工作表,默认取第一个
jxl.write.WritableSheet ws =wwb.createSheet("测试", 0);
// 插入行列
// 插入空白行
for (int i = ws.getRows(); i< 3; i++) {
ws.insertRow(i);
}
// 插入空白列
for (int i = ws.getColumns(); i< 3; i++) {
ws.insertColumn(i);
}
// 写入数据
String data ="666.00";
//保留两位小数,如果小数位为0则不显示
NumberFormat fivedps = newNumberFormat("#.##");
WritableCellFormatfivedpsFormat = new WritableCellFormat(fivedps);
jxl.write.Number doubleNum =new jxl.write.Number(0, 0, Double.valueOf(
data).doubleValue(),getCellStyle(fivedpsFormat, 1));
ws.addCell(doubleNum);
//保留两位小数,如果小数位不足两位,用0填充
NumberFormat fivedps1 = newNumberFormat("#.00");
WritableCellFormatfivedpsFormat1 = new WritableCellFormat(fivedps1);
jxl.write.Number doubleNum1 =new jxl.write.Number(1, 0, Double.valueOf(
data).doubleValue(),getCellStyle(fivedpsFormat1, 1));
ws.addCell(doubleNum1);
wwb.write();
wwb.close();
}
public WritableCellFormatgetCellStyle(WritableCellFormat wcf, int flag)
throwsWriteException {
wcf.setBorder(Border.ALL,BorderLineStyle.THIN);
// 设置单元格内容对齐方式
if (flag == 0) {
wcf.setAlignment(jxl.format.Alignment.LEFT);
} else if (flag == 1){
wcf.setAlignment(jxl.format.Alignment.RIGHT);
} else {
wcf.setAlignment(jxl.format.Alignment.CENTRE);
}
// 设置单元格内容为垂直居中
wcf.setVerticalAlignment(VerticalAlignment.CENTRE);
return wcf;
}
public static void main(String[] arg){
ExportExcel ee = newExportExcel();
try {
ee.exportExcel();
} catch (RowsExceededExceptione) {
e.printStackTrace();
} catch (BiffException e){
e.printStackTrace();
} catch (WriteException e){
e.printStackTrace();
} catch (IOException e){
e.printStackTrace();
}
}
}