`
tntxia
  • 浏览: 1485977 次
  • 性别: Icon_minigender_1
  • 来自: 深圳
社区版块
存档分类
最新评论

使用JXL读取Excel表格,拷贝、更新Excel工作薄

阅读更多
Java代码 复制代码
  1. /**  
  2. * <p>读取Excel表格,拷贝、更新Excel工作薄 </p>  
  3. * <p>Description: 可以读取Excel文件的内容,更新Excel工作薄  
  4. * </p>  
  5. * <p>Copyright: Copyright (c) Corparation 2005</p>  
  6. * <p>程序开发环境为eclipse</p>  
  7. * @author Walker  
  8. * @version 1.0  
  9. */  
  10. package cn.com.yitong.xls;   
  11.   
  12. import java.io.File;   
  13. import java.io.FileInputStream;   
  14. import java.io.InputStream;   
  15. import java.util.Vector;   
  16.   
  17. import cn.com.yitong.ChartImg;   
  18. import cn.com.yitong.VireObj;   
  19. import cn.com.yitong.platform.log.YTLogger;   
  20.   
  21. import <SPAN class=hilite1>jxl</SPAN>.CellType;   
  22. import <SPAN class=hilite1>jxl</SPAN>.Workbook;   
  23. import <SPAN class=hilite1>jxl</SPAN>.format.CellFormat;   
  24. import <SPAN class=hilite1>jxl</SPAN>.format.Colour;   
  25. import <SPAN class=hilite1>jxl</SPAN>.format.UnderlineStyle;   
  26. import <SPAN class=hilite1>jxl</SPAN>.write.Formula;   
  27. import <SPAN class=hilite1>jxl</SPAN>.write.Label;   
  28. import <SPAN class=hilite1>jxl</SPAN>.write.Number;   
  29. import <SPAN class=hilite1>jxl</SPAN>.write.WritableCell;   
  30. import <SPAN class=hilite1>jxl</SPAN>.write.WritableCellFormat;   
  31. import <SPAN class=hilite1>jxl</SPAN>.write.WritableFont;   
  32. import <SPAN class=hilite1>jxl</SPAN>.write.WritableImage;   
  33. import <SPAN class=hilite1>jxl</SPAN>.write.WritableSheet;   
  34. import <SPAN class=hilite1>jxl</SPAN>.write.WritableWorkbook;   
  35. import <SPAN class=hilite1>jxl</SPAN>.write.WriteException;   
  36. import <SPAN class=hilite1>jxl</SPAN>.write.biff.RowsExceededException;   
  37.   
  38. public class XLSDemo   
  39. {   
  40.     private static final int TITLE_LENGTH = 7;   
  41.     private static final int SHEET_WIDTH = 32;   
  42.     private static final int SHEET_HEIGHT = 116;   
  43.        
  44.     /**  
  45.      * 创建Excel  
  46.      */  
  47.     private void makeXls()   
  48.     {   
  49.         Workbook workbook = null;   
  50.         try  
  51.         {   
  52.             // 构建Workbook对象, 只读Workbook对象   
  53.             // 直接从本地文件创建Workbook, 从输入流创建Workbook   
  54.             InputStream ins = new FileInputStream("D:/Workspace/testproj/source.xls");   
  55.             workbook = Workbook.getWorkbook(ins);   
  56.   
  57.             // 利用已经创建的Excel工作薄创建新的可写入的Excel工作薄   
  58.             File outFile = new File("D:/Workspace/testproj/test.xls");   
  59.             WritableWorkbook wwb = Workbook.createWorkbook(outFile, workbook);   
  60.             // 读取第一张工作表   
  61.             WritableSheet dataSheet = wwb.getSheet(0);   
  62.             //  设置冻结单元格   
  63.             dataSheet.getSettings().setVerticalFreeze(7);   
  64.             dataSheet.getSettings().setHorizontalFreeze(2);   
  65.                
  66.             // 测试模拟数据   
  67.             Vector vecData = new Vector();   
  68.             for(int i = 0; i < 50; i ++)   
  69.             {   
  70.                 VireObj obj = new VireObj();   
  71.                 obj.setOrgNo("00" + i + "0");   
  72.                 obj.setOrgName("机构" + (i + 1));   
  73.                 obj.setOpenAcc((int)(100 * Math.random()));   
  74.                 obj.setDestoryAcc((int)(10 * Math.random()));   
  75.                 obj.setTotalAcc((int)(500 * Math.random()));   
  76.                 obj.setMonthInCount((int)(500 * Math.random()));   
  77.                 obj.setMonthInMoney(500 * Math.random());   
  78.                 obj.setMonthOutCount((int)(500 * Math.random()));   
  79.                 obj.setMonthOutMoney(500 * Math.random());   
  80.                    
  81.                 vecData.add(obj);   
  82.             }               
  83.             // 插入数据   
  84.             insertData(wwb, dataSheet, vecData);               
  85.             // 插入模拟图像数据   
  86.             Vector vecImg = new Vector();   
  87.             for(int i = 0; i < 3; i ++)   
  88.             {   
  89.                 ChartImg img = new ChartImg();   
  90.                 img.setImgTitle("图像" + (i + 1));   
  91.                 img.setImgName("D:/Workspace/testproj/images/barchart.png");   
  92.                 vecImg.add(img);   
  93.             }   
  94.             // 插入图表   
  95.             insertImgsheet(wwb, vecImg);   
  96.             //写入Excel对象   
  97.             wwb.write();   
  98.             wwb.close();   
  99.         } catch (Exception e)   
  100.         {   
  101.             YTLogger.logDebug(e);   
  102.         } finally  
  103.         {   
  104.             // 操作完成时,关闭对象,释放占用的内存空间   
  105.             workbook.close();   
  106.         }   
  107.     }   
  108.        
  109.     /**  
  110.      * 插入数据  
  111.      * @param wwb WritableWorkbook : 工作簿  
  112.      * @param dataSheet WritableSheet : 工作表  
  113.      * @throws RowsExceededException  
  114.      * @throws WriteException  
  115.      */  
  116.     private void insertData(WritableWorkbook wwb, WritableSheet dataSheet, Vector vecData) throws RowsExceededException, WriteException   
  117.     {   
  118.         // 获得标题单元格对象           
  119.         modiStrCell(dataSheet, 20"工商银行江苏省分行 个人网上银行业务种类/开销户明细报表(2005-12)"null);   
  120.         // 修改数据单元格数据   
  121.         for(int i = 0; i < vecData.size(); i ++)   
  122.         {   
  123.             VireObj obj = (VireObj)vecData.get(i);   
  124.             modiStrCell(dataSheet, 0, TITLE_LENGTH + i, obj.getOrgNo(), null);   
  125.             modiStrCell(dataSheet, 1, TITLE_LENGTH + i, obj.getOrgName(), null);   
  126.             modiNumCell(dataSheet, 2, TITLE_LENGTH + i, obj.getOpenAcc(), null);   
  127.             modiNumCell(dataSheet, 3, TITLE_LENGTH + i, obj.getDestoryAcc(), null);   
  128.             modiNumCell(dataSheet, 4, TITLE_LENGTH + i, obj.getTotalAcc(), null);   
  129.             modiNumCell(dataSheet, 5, TITLE_LENGTH + i, obj.getMonthInCount(), null);   
  130.             modiNumCell(dataSheet, 6, TITLE_LENGTH + i, obj.getTotalInMoney(), null);   
  131.             modiNumCell(dataSheet, 7, TITLE_LENGTH + i, obj.getMonthOutCount(), null);   
  132.             modiNumCell(dataSheet, 8, TITLE_LENGTH + i, obj.getMonthOutMoney(), null);   
  133.         }       
  134.         // 删除空行   
  135.         for (int j = vecData.size() + TITLE_LENGTH; j < SHEET_HEIGHT; j++)   
  136.         {   
  137.             dataSheet.removeRow(vecData.size() + TITLE_LENGTH);   
  138.         }           
  139.         // <SPAN class=hilite2>插入公式</SPAN>   
  140.         for(int i = 2; i < SHEET_WIDTH; i ++)   
  141.         {   
  142.             modiFormulaCell(dataSheet, i, vecData.size() + TITLE_LENGTH, 8, vecData.size() + TITLE_LENGTH, null);   
  143.         }           
  144.     }   
  145.   
  146.     /**  
  147.      * 修改字符单元格的值  
  148.      * @param dataSheet WritableSheet : 工作表  
  149.      * @param col int : 列  
  150.      * @param row int : 行  
  151.      * @param str String : 字符  
  152.      * @param format CellFormat : 单元格的样式  
  153.      * @throws RowsExceededException  
  154.      * @throws WriteException  
  155.      */  
  156.     private void modiStrCell(WritableSheet dataSheet, int col, int row, String str, CellFormat format) throws RowsExceededException, WriteException   
  157.     {   
  158.         // 获得单元格对象   
  159.         WritableCell cell = dataSheet.getWritableCell(col, row);   
  160.         // 判断单元格的类型, 做出相应的转化   
  161.         if (cell.getType() == CellType.EMPTY)   
  162.         {   
  163.             Label lbl = new Label(col, row, str);   
  164.             if(null != format)   
  165.             {   
  166.                 lbl.setCellFormat(format);   
  167.             } else  
  168.             {   
  169.                 lbl.setCellFormat(cell.getCellFormat());   
  170.             }   
  171.             dataSheet.addCell(lbl);   
  172.         } else if (cell.getType() == CellType.LABEL)   
  173.         {   
  174.             Label lbl = (Label)cell;   
  175.             lbl.setString(str);   
  176.         } else if (cell.getType() == CellType.NUMBER)   
  177.         {   
  178.             // 数字单元格修改   
  179.             Number n1 = (Number)cell;   
  180.             n1.setValue(42.05);   
  181.         }   
  182.     }   
  183.        
  184.     /**  
  185.      * 修改数字单元格的值  
  186.      * @param dataSheet WritableSheet : 工作表  
  187.      * @param col int : 列  
  188.      * @param row int : 行  
  189.      * @param num double : 数值  
  190.      * @param format CellFormat : 单元格的样式  
  191.      * @throws RowsExceededException  
  192.      * @throws WriteException  
  193.      */  
  194.     private void modiNumCell(WritableSheet dataSheet, int col, int row, double num, CellFormat format) throws RowsExceededException, WriteException   
  195.     {   
  196.         // 获得单元格对象   
  197.         WritableCell cell = dataSheet.getWritableCell(col, row);   
  198.         // 判断单元格的类型, 做出相应的转化   
  199.         if (cell.getType() == CellType.EMPTY)   
  200.         {   
  201.             Number lbl = new Number(col, row, num);   
  202.             if(null != format)   
  203.             {   
  204.                 lbl.setCellFormat(format);   
  205.             } else  
  206.             {   
  207.                 lbl.setCellFormat(cell.getCellFormat());   
  208.             }   
  209.             dataSheet.addCell(lbl);   
  210.         } else if (cell.getType() == CellType.NUMBER)   
  211.         {   
  212.             // 数字单元格修改   
  213.             Number lbl = (Number)cell;   
  214.             lbl.setValue(num);   
  215.         } else if (cell.getType() == CellType.LABEL)   
  216.         {   
  217.             Label lbl = (Label)cell;   
  218.             lbl.setString(String.valueOf(num));   
  219.         }   
  220.     }   
  221.        
  222.     /**  
  223.      * 修改公式单元格的值  
  224.      * @param dataSheet WritableSheet : 工作表  
  225.      * @param col int : 列  
  226.      * @param row int : 行  
  227.      * @param startPos int : 开始位置  
  228.      * @param endPos int : 结束位置  
  229.      * @param format  
  230.      * @throws RowsExceededException  
  231.      * @throws WriteException  
  232.      */  
  233.     private void modiFormulaCell(WritableSheet dataSheet, int col, int row, int startPos, int endPos, CellFormat format) throws RowsExceededException, WriteException   
  234.     {   
  235.         String f = getFormula(col, row, startPos, endPos);   
  236.         // <SPAN class=hilite2>插入公式</SPAN>(只支持插入,不支持修改)   
  237.         WritableCell cell = dataSheet.getWritableCell(col, row);   
  238.         if (cell.getType() == CellType.EMPTY)   
  239.         {                       
  240.             // 公式单元格   
  241.             Formula lbl = new Formula(col, row, f);   
  242.             if(null != format)   
  243.             {   
  244.                 lbl.setCellFormat(format);   
  245.             } else  
  246.             {   
  247.                 lbl.setCellFormat(cell.getCellFormat());   
  248.             }   
  249.             dataSheet.addCell(lbl);   
  250.         } else if (cell.getType() == CellType.STRING_FORMULA)   
  251.         {   
  252.             YTLogger.logWarn("Formula modify not supported!");   
  253.         }   
  254.     }   
  255.        
  256.     /**  
  257.      * 得到公式  
  258.      * @param col int : 列  
  259.      * @param row int : 行  
  260.      * @param startPos int : 开始位置  
  261.      * @param endPos int : 结束位置  
  262.      * @return String  
  263.      * @throws RowsExceededException  
  264.      * @throws WriteException  
  265.      */  
  266.     private String getFormula(int col, int row, int startPos, int endPos)   
  267.             throws RowsExceededException, WriteException   
  268.     {   
  269.         char base = 'A';   
  270.         char c1 = base;   
  271.         StringBuffer formula = new StringBuffer(128);   
  272.         // 组装公式   
  273.         formula.append("SUM(");   
  274.         if (col <= 25)   
  275.         {   
  276.             c1 = (char) (col % 26 + base);   
  277.             formula.append(c1).append(startPos).append(":")   
  278.                    .append(c1).append(endPos).append(")");   
  279.         } else if (col > 25)   
  280.         {   
  281.             char c2 = (char) ((col - 26) / 26 + base);   
  282.             c1 = (char) ((col - 26) % 26 + base);   
  283.             formula.append(c2).append(c1).append(startPos).append(":")   
  284.                    .append(c2).append(c1).append(endPos).append(")");   
  285.         }   
  286.   
  287.         return formula.toString();   
  288.     }   
  289.        
  290.     /**  
  291.      * 插入图表工作表  
  292.      * @param wwb WritableWorkbook : 工作簿  
  293.      * @param vecImg Vector : 图像链表  
  294.      * @throws RowsExceededException  
  295.      * @throws WriteException  
  296.      */  
  297.     private void insertImgsheet(WritableWorkbook wwb, Vector vecImg)   
  298.             throws RowsExceededException, WriteException   
  299.     {   
  300.         // 插入图像   
  301.         WritableSheet imgSheet;   
  302.         if((wwb.getSheets()).length < 2)   
  303.         {   
  304.             imgSheet = wwb.createSheet("图表"1);   
  305.         } else  
  306.         {   
  307.             imgSheet = wwb.getSheet(1);   
  308.         }   
  309.            
  310.         for (int i = 0; i < vecImg.size(); i++)   
  311.         {   
  312.             ChartImg chart = (ChartImg) vecImg.get(i);   
  313.             // 插入图像标题   
  314.             Label lbl = new Label(02 + 20 * i, chart.getImgTitle());   
  315.             WritableFont font = new WritableFont(WritableFont.ARIAL,   
  316.                     WritableFont.DEFAULT_POINT_SIZE, WritableFont.NO_BOLD, false,   
  317.                     UnderlineStyle.NO_UNDERLINE, Colour.DARK_BLUE2);   
  318.             WritableCellFormat background = new WritableCellFormat(font);   
  319.             background.setWrap(true);   
  320.             background.setBackground(Colour.GRAY_25);   
  321.             imgSheet.mergeCells(02 + 20 * i, 92 + 20 * i);   
  322.             lbl.setCellFormat(background);   
  323.             imgSheet.addCell(lbl);   
  324.             // 插入图像单元格   
  325.             insertImgCell(imgSheet, 24 + 20 * i, 815, chart.getImgName());   
  326.         }   
  327.     }   
  328.   
  329.     /**  
  330.      * 插入图像到单元格(图像格式只支持png)  
  331.      * @param dataSheet WritableSheet : 工作表  
  332.      * @param col int : 列  
  333.      * @param row int : 行  
  334.      * @param width int : 宽  
  335.      * @param height int : 高  
  336.      * @param imgName String : 图像的全路径  
  337.      * @throws RowsExceededException  
  338.      * @throws WriteException  
  339.      */  
  340.     private void insertImgCell(WritableSheet dataSheet, int col, int row, int width,   
  341.             int height, String imgName) throws RowsExceededException, WriteException   
  342.     {   
  343.         File imgFile = new File(imgName);   
  344.         WritableImage img = new WritableImage(col, row, width, height, imgFile);   
  345.         dataSheet.addImage(img);   
  346.     }   
  347.        
  348.     /**  
  349.      * 测试  
  350.      * @param args  
  351.      */  
  352.     public static void main(String[] args)   
  353.     {   
  354.         XLSDemo demo = new XLSDemo();   
  355.         demo.makeXls();   
  356.     }   
  357. }  
分享到:
评论

相关推荐

Global site tag (gtag.js) - Google Analytics