java產生excel檔案工具類執行個體

來源:互聯網
上載者:User

標籤: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);}}


相關文章

聯繫我們

該頁面正文內容均來源於網絡整理,並不代表阿里雲官方的觀點,該頁面所提到的產品和服務也與阿里云無關,如果該頁面內容對您造成了困擾,歡迎寫郵件給我們,收到郵件我們將在5個工作日內處理。

如果您發現本社區中有涉嫌抄襲的內容,歡迎發送郵件至: info-contact@alibabacloud.com 進行舉報並提供相關證據,工作人員會在 5 個工作天內聯絡您,一經查實,本站將立刻刪除涉嫌侵權內容。

A Free Trial That Lets You Build Big!

Start building with 50+ products and up to 12 months usage for Elastic Compute Service

  • Sales Support

    1 on 1 presale consultation

  • After-Sales Support

    24/7 Technical Support 6 Free Tickets per Quarter Faster Response

  • Alibaba Cloud offers highly flexible support services tailored to meet your exact needs.