您的位置:首页 > 编程语言 > Java开发

java生成excel文件工具类实例

2014-08-11 14:20 127 查看
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;

import org.apache.log4j.Logger;

public class ExcelUtils {

static private Logger logger = Logger.getLogger(ExcelUtils.class);

static public int SUCCESS = 0;

static public int ERROR = -1;

/**

* 创建单个sheet的excel文件,自己指定路径,用二维数组来映射相应的单元格

**/

static public int createExcel(String fileRootPath,String fileName,String sheetName,String[][] dataArr){

int result = ERROR;

try {

if(fileRootPath == null || "".equals(fileRootPath) || fileName == null || "".equals(fileName) ){

throw new Exception("创建excel文件错误:createExcel方法参数值为空!");

}

if(dataArr == null || dataArr[0] == null){

throw new Exception("输入的参数dataArr错误!");

}

String filePath = fileRootPath + fileName;

File file = new File(fileRootPath);

if(!file.exists()){

file.mkdirs();

}

WritableWorkbook book = Workbook.createWorkbook(new File(filePath));

if(sheetName == null || "".equals(sheetName)){

sheetName = "第一页";

}

// 生成名为sheetName的工作表,参数0表示这是第一页

WritableSheet sheet = book.createSheet(sheetName , 0);

// 在Label对象的构造子中指名单元格位置是第一列第一行(0,0)

// 以及单元格内容为test

for(int i=0 ;i<dataArr.length;i++){

for(int j=0;j<dataArr[0].length;j++){

Label label = new Label(j, i, dataArr[i][j]);

sheet.addCell(label);// 将定义好的单元格添加到工作表中

}

}

book.write();

book.close();

result = SUCCESS;

} catch (IOException e) {

logger.error("excel文件路径错误!");

logger.error(e.toString());

return result;

} catch (RowsExceededException e) {

logger.error("创建excel时,行超过!");

logger.error(e.toString());

return result;

} catch (WriteException e) {

logger.error("创建excel时,写入错误!");

logger.error(e.toString());

return result;

}catch (Exception e) {

logger.error(e.toString());

return result;

}

return result;

}

public static void main(String args[]) {

String[][] myarr = new String[2][3];

myarr[0][0]="11";

myarr[0][1]="12";

myarr[0][2]="13";

myarr[1][0]="21";

myarr[1][1]="22";

myarr[1][2]="23";

ExcelUtils.createExcel("D:/test/", "test.xls", "代理商账户列表", myarr);

}

}
内容来自用户分享和网络整理,不保证内容的准确性,如有侵权内容,可联系管理员处理 点击这里给我发消息
标签: