展开全部
JCOM生成Excel2
1.import java.io.File;
2.
3.import jp.ne.so_net.ga2.no_ji.jcom.IDispatch;
4.import jp.ne.so_net.ga2.no_ji.jcom.JComException;
5.import jp.ne.so_net.ga2.no_ji.jcom.ReleaseManager;
6./**
7. * 使用jCom实现写excel文件的另一种方式(IDispatch)
8. * @author admin
9. *
10. */
11.public class TestJcom2 {
12.
13. private static ReleaseManager rm = null;
14. private static IDispatch xlsApp = null;
15. private static IDispatch excel = null;
16. private static IDispatch workbook = null;// 工作32313133353236313431303231363533e59b9ee7ad9431333262373961薄
17. private static IDispatch sheets = null;// 所有工作表(是一个数组形式)
18. private static IDispatch sheet = null;// 单个工作表
19. private static IDispatch currentSheet = null;// 当前活动的工作表
20.
21. /**
22. * @param args
23. */
24. public static void main(String[] args) {
25.
26. rm = new ReleaseManager();// 查找JCOM能够操作的组件
27. try {
28. System.out.println("----------1--------------");
29. xlsApp = new IDispatch(rm, "Excel.Application");
30. System.out.println("----------2--------------");
31. excel = (IDispatch) xlsApp.get("Workbooks");// 得到工作薄
32. System.out.println("----------3--------------");
33. xlsApp.put("Visible", new java.lang.Boolean(false)); // 设置当前对象是否可见
34. System.out.println("----------4--------------");
35.
36. File f = new File("D:\\testExcel.xls" );
37. System.out.println("----------5--------------");
38. if (f.exists()) {}//判断文件是否存在
39.
40. workbook = (IDispatch) excel.method("open",
41. new Object[] {"D:\\testExcel.xls" }); // 打开工作薄
42. System.out.println("----------6--------------");
43.
44. sheets = (IDispatch) workbook.get("Sheets");
45. System.out.println("----------7--------------");
46. int sheetsCount = Integer.parseInt(sheets.get("Count").toString());// 得到工作表的数量
47. System.out.println("----------8--------------");
48. for (int sheetInx = 1; sheetInx <= sheetsCount; sheetInx++) { // 得到各个工作表的名称
49. System.out.println("----------9--------------");
50. sheet = (IDispatch) sheets.get("item",//按照工作表索引得到工作表
51. new Object[] { new Integer(sheetInx) });
52. System.out.println("----------10--------------");
53. String sheetName = sheet.get("name").toString();
54. System.out.println("----------11--------------");
55. sheet.put("name", "Nsheet"+sheetInx);//修改当前工作表的名称
56. System.out.println("----------12--------------");
57.
58. }
59. currentSheet = (IDispatch) xlsApp.get("ActiveSheet"); //得到当前获得的工作表
60. currentSheet.put("name", "new sheet");
61.
62. } catch (JComException e) {
63. System.out.println("--------Error-----------");
64. e.printStackTrace();
65. }
66. }
67.
68.}
本回答由提问者推荐
已赞过
已踩过<
你对这个回答的评价是?
评论
收起