標籤:java 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;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)// 以及儲存格內容為testfor(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);}}