日期:2014-05-20 浏览次数:20791 次
package com.test;
import java.io.File;
import java.io.FileOutputStream;
import java.util.ArrayList;
import java.util.List;
import jxl.Workbook;
import jxl.format.Alignment;
import jxl.format.Colour;
import jxl.format.UnderlineStyle;
import jxl.write.Label;
import jxl.write.Number;
import jxl.write.WritableCellFormat;
import jxl.write.WritableFont;
import jxl.write.WritableSheet;
import jxl.write.WritableWorkbook;
/**
* 生成excel的工具类,不用模板
* @version 2.0
* */
public class ExportExcel {
private static ExportExcel bean = new ExportExcel();
public static ExportExcel getBean() {
return bean;
}
private FileOutputStream output;
private WritableWorkbook book;
/**
* 导出excel生成文件
* @param base 根目录(文件存放的目录)
* @param fileName 文件名
* @param fullDatas 要导出的数据(这里必须存放String类型的数组)
* @param title 文件的标题(第一行)
* @param coteWidths 每一列的宽度
* @param titles 表头标题
* @param numCote 需要数字格式化的列的索引
* @return String 返回输出文件的物理路径
* */
@SuppressWarnings("unchecked")
public String reportExcel(String base, String fileName, List fullDatas,
String title, int[] coteWidths, String[] titles, int[] numCote) {
try {
createFolder(base);//如果文件夹不存在就创建
String filePath = base + fileName;//输出文件路径
WritableCellFormat cellFormat = new WritableCellFormat();
cellFormat.setAlignment(Alignment.CENTRE);//居中显示
WritableSheet sheet = getExcel(filePath, title, coteWidths, titles);//获得工作簿
if(null != sheet){
for(int i = 0; i < fullDatas.size(); i++){
String[] fullData = (String[]) fullDatas.get(i);
if(fullData.length == coteWidths.length){//确保数据个数一致
for (int j = 0; j < fullData.length; j++) {
boolean isNumeric = false;//判断该列是否需要数字化格式
if(null != numCote && numCote.length > 0){
for(int c = 0; c < numCote.length; c++){
if(j == numCote[c]){
isNumeric = true;
break;
}
}
}
if(isNumeric){
Double numeric = Double.parseDouble(fullData[j]);
Number number = new Number(j, i + 2, numeric, cellFormat);
sheet.addCell(number);//数字格式化
}else {
Label label = new Label(j, i + 2, fullData[j], cellFormat);
sheet.addCell(label);//文本数据
}
}
}
}
}
book.write();
book.close();
output.close();
return filePath;
} catch (Exception e) {
e.printStackTrace();