How to use JCOM to realize imitating Excel programming in Java
This article mainly introduces how to use JCOM to achieve imitation Excel programming in Java, which has a certain reference value, and interested friends can refer to it. I hope you can learn a lot after reading this article.
Key points for Excel programming with JCOM and JXL in JAVA:
(1) have jdom-1.0.jar,jxl-2.5.5.jar,jcom-2.2.4.jar,jcom.dll under your lib.
(2) put the jcom.dll in the bin directory of your JDK or under the windows of the system disk (it is recommended to put it under the BIN of JDK)
After putting all the above JAR packages away, start writing the utility classes in the application (to make it clear that all you get in JCOM are IDispatch objects, the following will throw a JComException exception)
(1) first of all, we should judge whether an incoming path is Word or Excel or something else.
If (path.endsWith (".doc")) {
.
}
Note: if excel suffix is ".xls"
(2) then you have to have two objects:
ReleaseManager rm = new ReleaseManager ()
IDispatch xlsApp=null
Note: ReleaseManager is equivalent to a container and establishes a relationship with all the JCOM groups on your machine. According to the parameters you pass, he will look for all the components on your machine that can be operated by JCOM.
IDispatch can be understood as an object, and everything is an object.
(3) you have to let him know that you want to interact with EXCEL. You have to do this.
XlsApp = new IDispatch (rm, "Excel.Application")
(4) then get a Workbooks (workbook)
IDispatch excel = (IDispatch) xlsApp.get ("Workbooks")
(5) set whether the current object is visible
XlsApp.put ("Visible", new java.lang.Boolean (false))
(6) Open the workbook after you get it.
IDispatch workbook = (IDispatch) excel.method ("open", new Object [] {FilePath (path where EXCEL is stored)})
(7) determine whether the file exists. If so, delete it.
File f = new File (outPath)
If (f.exists ())
F.delete ()
(8) Save the workbook as
Workbook.method ("saveAs", new Object [] {outPath, new Integer (9)})
(9) get all the worksheets under a workbook (workbook) (Sheets)
IDispatch sheets = (IDispatch) workbook.get ("Sheets")
Note: what you get is an array
(10) get the total number of worksheets (Sheets)
Int sheetsCount = Integer.parseInt (sheets.get ("Count") .toString ())
(11) get the name of each sheet (Sheets)
For (int sheetInx=1;sheetInx