今天在做一个自动化生成SDD文档的小工具,通过Word的模板,前台通过Flex填入数据,最后将Word文档填写好。
以下是一部分代码,关于表格自动追加表格内容
Java代码
1. importjava.util.ArrayList;
2.
3. importcom.heavenlake.wordapi.Document;
4.
5. publicclasstest
6. {
7. publictest()
8. {
9. Documentdoc=null;
10. try{
11. doc=newDocument();
12. doc.newDoc("e:/test4.doc");
13. doc.insertln("测试文档");
14. doc.insertln("天池软件产品列表");
15. //doc.saveAs("e:/test2.doc");
16. ArrayListtableData=newArrayList(3);
17. String[]title={
18. "序号","代码","名称","网址"};
19. tableData.add(title);
20. String[]field1={
21. "1","751002","天池软件自动化生产平台","www.heavenlake.com"};
22. tableData.add(field1);
23. String[]field2={
24. "2","751004","产品数据管理系统","pdm.heavenlake.com"};
25. tableData.add(field2);
26.
27. doc.insert(tableData,"流行型");
28.
29. doc.insertln();
30.
31.
32. ArrayListtableData1=newArrayList(3);
33.
34. String[]field3={
35. "1","751002","天池软件自动化生产平台","www.heavenlake.com"};
36. tableData1.add(field3);
37. String[]field4={
38. "2","751004","产品数据管理系统","pdm.heavenlake.com"};
39. tableData1.add(field4);
40. doc.replaceTable(1,4,tableData1);
41.
42. }catch(Exceptione)
43. {
44. e.printStackTrace();
45. }finally
46. {
47. try
48. {
49. if(doc!=null)
50. doc.close(true);
51. }catch(Exceptione)
52. {
53. e.printStackTrace();
54. }
55.
56. }
57.
58. }
59.
60. publicstaticvoidmain(String[]args)
61. {
62. testtest1=newtest();
63. }
64.
65. }
jacob-1.15-M3.zip
jacob-1.15-M3-x86.dllcopy到c://windows/system32
引入jacob.jar
示例代码
viewplain
1. importjava.io.File;
2. importcom.jacob.activeX.ActiveXComponent;
3. importcom.jacob.com.Dispatch;
4. importcom.jacob.com.Variant;
5. classWordBean{
6. //代表一个word程序
7. privateActiveXComponentMsWordApp=null;
8. //代表进行处理的word文档
9. privateDispatchdocument=null;
10. publicWordBean(){
11. //OpenWordifwe/'venotdoneitalready
12. if(MsWordApp==null){
13. MsWordApp=newActiveXComponent("Word.Application");
14. }
15. }
16. //设置是否在前台打开word程序,
17. publicvoidsetVisible(booleanvisible){
18. MsWordApp.setProperty("Visible",newVariant(visible));
19. //这一句作用相同
20. //Dispatch.put(MsWordApp,"Visible",newVariant(visible));
21. }
22. //创建一个新文档
23. publicvoidcreateNewDocument(){
24. //FindtheDocumentscollectionobjectmaintainedbyWord
25. //documents表示word的所有文档窗口,(word是多文档应用程序)
26. Dispatchdocuments=Dispatch.get(MsWordApp,"Documents").toDispatch();
27. //CalltheAddmethodoftheDocumentscollectiontocreate
28. //anewdocumenttoedit
29. document=Dispatch.call(documents,"Add").toDispatch();
30. }
31. //打开一个存在的word文档,并用document引用引用它
32. publicvoidopenFile(StringwordFilePath){
33. //FindtheDocumentscollectionobjectmaintainedbyWord
34. //documents表示word的所有文档窗口,(word是多文档应用程序)
35. Dispatchdocuments=Dispatch.get(MsWordApp,"Documents").toDispatch();
36. document=Dispatch.call(documents,"Open",wordFilePath,
37. newVariant(true)/*是否进行转换ConfirmConversions*/,
38. newVariant(false)/*是否只读*/).toDispatch();
39. //document=Dispatch.invoke(documents,"Open",Dispatch.Method,
40. //newObject[]{wordFilePath,newVariant(true),
41. //newVariant(false)
42. //},newint[1]).toDispatch();
43. }
44. //向document中插入文本内容
45. publicvoidinsertText(StringtextToInsert){
46. //GetthecurrentselectionwithinWordatthemoment.
47. //anewdocumenthasjustbeencreatedthenthiswillbeat
48. //thetopofthenewdoc获得选中的内容,如果是一个新创建的文件,因里面无内容,则光标应处于文件开头处
49. Dispatchselection=Dispatch.get(MsWordApp,"Selection").toDispatch();
50. //取消选中,应该就是移动光标,否则新添加的内容会覆盖选中的内容
51. Dispatch.call(selection,"MoveRight",newVariant(1),newVariant(1));
52. //Putthespecifiedtextattheinsertionpoint
53. Dispatch.put(selection,"Text",textToInsert);
54. //取消选中,应该就是移动光标
55. Dispatch.call(selection,"MoveRight",newVariant(1),newVariant(1));
56. }
57. //向文档中添加一个图片,
58. publicvoidinsertJpeg(StringjpegFilePath){
59. Dispatchselection=Dispatch.get(MsWordApp,"Selection").toDispatch();
60. Dispatchimage=Dispatch.get(selection,"InLineShapes").toDispatch();
61. Dispatch.call(image,"AddPicture",jpegFilePath);
62. }
63. //段落的处理,插入格式化的文本
64. publicvoidinsertFormatStr(Stringtext){
65. DispatchwordContent=Dispatch.get(document,"Content").toDispatch();//取得word文件的内容
66. Dispatch.call(wordContent,"InsertAfter",text);//插入一个段落到最后
67. Dispatchparagraphs=Dispatch.get(wordContent,"Paragraphs")
68. .toDispatch();//所有段落
69. intparagraphCount=Dispatch.get(paragraphs,"Count").changeType(
70. Variant.VariantInt).getInt();//一共的段落数
71. //找到刚输入的段落,设置格式
72. DispatchlastParagraph=Dispatch.call(paragraphs,"Item",
73. newVariant(paragraphCount)).toDispatch();//最后一段(也就是刚插入的)
74. //Range对象表示文档中的一个连续范围,由一个起始字符位置和一个终止字符位置定义
75. DispatchlastParagraphRange=Dispatch.get(lastParagraph,"Range")
76. .toDispatch();
77. Dispatchfont=Dispatch.get(lastParagraphRange,"Font").toDispatch();
78. Dispatch.put(font,"Bold",newVariant(true));//设置为黑体
79. Dispatch.put(font,"Italic",newVariant(true));//设置为斜体
80. Dispatch.put(font,"Name",newVariant("宋体"));//
81. Dispatch.put(font,"Size",newVariant(12));//小四
82. Dispatchselection=Dispatch.get(MsWordApp,"Selection").toDispatch();
83. Dispatch.call(selection,"TypeParagraph");//插入一个空行
84. Dispatchalignment=Dispatch.get(selection,"ParagraphFormat")
85. .toDispatch();//段落格式
86. Dispatch.put(alignment,"Alignment","2");//(1:置中2:靠右3:靠左)
87. }
88. //word中在对表格进行遍历的时候,是先列后行先column后cell
89. //另外下标从1开始
90. publicvoidinsertTable(StringtableTitle,introw,intcolumn){
91. Dispatchselection=Dispatch.get(MsWordApp,"Selection").toDispatch();//输入内容需要的对象
92. Dispatch.call(selection,"TypeText",tableTitle);//写入标题内容//标题格行
93. Dispatch.call(selection,"TypeParagraph");//空一行段落
94. Dispatch.call(selection,"TypeParagraph");//空一行段落
95. Dispatch.call(selection,"MoveDown");//游标往下一行
96. //建立表格
97. Dispatchtables=Dispatch.get(document,"Tables").toDispatch();
98. //intcount=Dispatch.get(tables,
99. //"Count").changeType(Variant.VariantInt).getInt();//document中的表格数量
100. //Dispatchtable=Dispatch.call(tables,"Item",newVariant(
101. //1)).toDispatch();//文档中第一个表格
102. Dispatchrange=Dispatch.get(selection,"Range").toDispatch();///当前光标位置或者选中的区域
103. DispatchnewTable=Dispatch.call(tables,"Add",range,
104. newVariant(row),newVariant(column),newVariant(1))
105. .toDispatch();//设置row,column,表格外框宽度
106. Dispatchcols=Dispatch.get(newTable,"Columns").toDispatch();//此表的所有列,
107. intcolCount=Dispatch.get(cols,"Count").changeType(
108. Variant.VariantInt).getInt();//一共有多少列实际上这个数==column
109. System.out.println(colCount+"列");
110. for(inti=1;i<=colCount;i++){//循环取出每一列
111. Dispatchcol=Dispatch.call(cols,"Item",newVariant(i))
112. .toDispatch();
113. Dispatchcells=Dispatch.get(col,"Cells").toDispatch();//当前列中单元格
114. intcellCount=Dispatch.get(cells,"Count").changeType(
115. Variant.VariantInt).getInt();//当前列中单元格数实际上这个数等于row
116. for(intj=1;j<=cellCount;j++){//每一列中的单元格数
117. //Dispatchcell=Dispatch.call(cells,"Item",new
118. //Variant(j)).toDispatch();//当前单元格
119. //Dispatchcell=Dispatch.call(newTable,"Cell",new
120. //Variant(j),newVariant(i)).toDispatch();//取单元格的另一种方法
121. //Dispatch.call(cell,"Select");//选中当前单元格
122. //Dispatch.put(selection,"Text",
123. //"第"+j+"行,第"+i+"列");//往选中的区域中填值,也就是往当前单元格填值
124. putTxtToCell(newTable,j,i,"第"+j+"行,第"+i+"列");//与上面四句的作用相同
125. }
126. }
127. }
128. /***/
129. /**
130. *在指定的单元格里填写数据
131. *
132. *@paramtableIndex
133. *@paramcellRowIdx
134. *@paramcellColIdx
135. *@paramtxt
136. */
137. publicvoidputTxtToCell(Dispatchtable,intcellRowIdx,intcellColIdx,
138. Stringtxt){
139. Dispatchcell=Dispatch.call(table,"Cell",newVariant(cellRowIdx),
140. newVariant(cellColIdx)).toDispatch();
141. Dispatch.call(cell,"Select");
142. Dispatchselection=Dispatch.get(MsWordApp,"Selection").toDispatch();//输入内容需要的对象
143. Dispatch.put(selection,"Text",txt);
144. }
145. /***/
146. /**
147. *在指定的单元格里填写数据
148. *
149. *@paramtableIndex
150. *@paramcellRowIdx
151. *@paramcellColIdx
152. *@paramtxt
153. */
154. publicvoidputTxtToCell(inttableIndex,intcellRowIdx,intcellColIdx,
155. Stringtxt){
156. //所有表格
157. Dispatchtables=Dispatch.get(document,"Tables").toDispatch();
158. //要填充的表格
159. Dispatchtable=Dispatch.call(tables,"Item",newVariant(tableIndex))
160. .toDispatch();
161. Dispatchcell=Dispatch.call(table,"Cell",newVariant(cellRowIdx),
162. newVariant(cellColIdx)).toDispatch();
163. Dispatch.call(cell,"Select");
164. Dispatchselection=Dispatch.get(MsWordApp,"Selection").toDispatch();//输入内容需要的对象
165. Dispatch.put(selection,"Text",txt);
166. }
167. //合并两个单元格
168. publicvoidmergeCell(Dispatchcell1,Dispatchcell2){
169. Dispatch.call(cell1,"Merge",cell2);
170. }
171. publicvoidmergeCell(Dispatchtable,introw1,intcol1,introw2,intcol2){
172. Dispatchcell1=Dispatch.call(table,"Cell",newVariant(row1),
173. newVariant(col1)).toDispatch();
174. Dispatchcell2=Dispatch.call(table,"Cell",newVariant(row2),
175. newVariant(col2)).toDispatch();
176. mergeCell(cell1,cell2);
177. }
178. publicvoidmergeCellTest(){
179. Dispatchtables=Dispatch.get(document,"Tables").toDispatch();
180. inttableCount=Dispatch.get(tables,"Count").changeType(
181. Variant.VariantInt).getInt();//document中的表格数量
182. Dispatchtable=Dispatch.call(tables,"Item",newVariant(tableCount))
183. .toDispatch();//文档中最后一个table
184. mergeCell(table,1,1,1,2);//将table中x=1,y=1与x=1,y=2的两个单元格合并
185. }
186. //========================================================
187. /***/
188. /**
189. *把选定的内容或光标插入点向上移动
190. *
191. *@parampos
192. *移动的距离
193. */
194. publicvoidmoveUp(intpos){
195. Dispatchselection=Dispatch.get(MsWordApp,"Selection").toDispatch();//输入内容需要的对象
196. for(inti=0;i<pos;i++){
197. //MoveDownMoveLeftmoveRight
198. //moveStart(Dispatch.call(selection,"HomeKey",newVariant(6));
199. //)
200. //moveEndDispatch.call(selection,"EndKey",newVariant(6));
201. Dispatch.call(selection,"MoveUp");
202. }
203. }
204. /***/
205. /**
206. *从选定内容或插入点开始查找文本
207. *
208. *@paramtoFindText
209. *要查找的文本
210. *@returnbooleantrue-查找到并选中该文本,false-未查找到文本
211. */
212. publicbooleanfind(StringtoFindText){
213. if(toFindText==null||toFindText.equals(""))
214. returnfalse;
215. Dispatchselection=Dispatch.get(MsWordApp,"Selection").toDispatch();//输入内容需要的对象
216. //从selection所在位置开始查询
217. Dispatchfind=Dispatch.call(selection,"Find").toDispatch();
218. //设置要查找的内容
219. Dispatch.put(find,"Text",toFindText);
220. //向前查找
221. Dispatch.put(find,"Forward","True");
222. //设置格式
223. Dispatch.put(find,"Format","True");
224. //大小写匹配
225. Dispatch.put(find,"MatchCase","True");
226. //全字匹配
227. Dispatch.put(find,"MatchWholeWord","True");
228. //查找并选中
229. returnDispatch.call(find,"Execute").getBoolean();
230. }
231. /***/
232. /**
233. *把选定选定内容设定为替换文本
234. *
235. *@paramtoFindText
236. *查找字符串
237. *@paramnewText
238. *要替换的内容
239. *@return
240. */
241. publicbooleanreplaceText(StringtoFindText,StringnewText){
242. if(!find(toFindText))
243. returnfalse;
244. Dispatchselection=Dispatch.get(MsWordApp,"Selection").toDispatch();//输入内容需要的对象
245. Dispatch.put(selection,"Text",newText);
246. returntrue;
247. }
248. publicvoidprintFile(){
249. //Justprintthecurrentdocumenttothedefaultprinter
250. Dispatch.call(document,"PrintOut");
251. }
252. //保存文档的更改
253. publicvoidsave(){
254. Dispatch.call(document,"Save");
255. }
256. publicvoidsaveFileAs(Stringfilename){
257. Dispatch.call(document,"SaveAs",filename);
258. }
259. publicvoidcloseDocument(){
260. //Closethedocumentwithoutsavingchanges
261. //0=wdDoNotSaveChanges
262. //-1=wdSaveChanges
263. //-2=wdPromptToSaveChanges
264. Dispatch.call(document,"Close",newVariant(0));
265. document=null;
266. }
267. publicvoidcloseWord(){
268. Dispatch.call(MsWordApp,"Quit");
269. MsWordApp=null;
270. document=null;
271. }
272. //设置wordApp打开后窗口的位置
273. publicvoidsetLocation(){
274. DispatchactiveWindow=Dispatch.get(MsWordApp,"Application")
275. .toDispatch();
276. Dispatch.put(activeWindow,"WindowState",newVariant(1));//0=default
277. //1=maximize
278. //2=minimize
279. Dispatch.put(activeWindow,"Top",newVariant(0));
280. Dispatch.put(activeWindow,"Left",newVariant(0));
281. Dispatch.put(activeWindow,"Height",newVariant(600));
282. Dispatch.put(activeWindow,"width",newVariant(800));
283. }
284. }
285. publicclassJacobTest2{
286. publicstaticvoidcreateANewFileTest(){
287. WordBeanwordBean=newWordBean();
288. //word.openWord(true);//打开word程序
289. wordBean.setVisible(true);
290. wordBean.createNewDocument();//创建一个新文档
291. wordBean.setLocation();//设置打开后窗口的位置
292. wordBean.insertText("你好");//向文档中插入字符
293. wordBean.insertJpeg("D:"+File.separator+"a.jpg");//插入图片
294. //如果,想保存文件,下面三句
295. //word.saveFileAs("d://a.doc");
296. //word.closeDocument();
297. //word.closeWord();
298. }
299. publicstaticvoidopenAnExistsFileTest(){
300. WordBeanwordBean=newWordBean();
301. wordBean.setVisible(true);//是否前台打开word程序,或者后台运行
302. wordBean.openFile("d://a.doc");
303. wordBean.insertJpeg("D:"+File.separator+"a.jpg");//插入图片(注意刚打开的word
304. //,光标处于开头,故,图片在最前方插入)
305. wordBean.save();
306. wordBean.closeDocument();
307. wordBean.closeWord();
308. }
309. publicstaticvoidinsertFormatStr(Stringstr){
310. WordBeanwordBean=newWordBean();
311. wordBean.setVisible(true);//是否前台打开word程序,或者后台运行
312. wordBean.createNewDocument();//创建一个新文档
313. wordBean.insertFormatStr(str);//插入一个段落,对其中的字体进行了设置
314. }
315. publicstaticvoidinsertTableTest(){
316. WordBeanwordBean=newWordBean();
317. wordBean.setVisible(true);//是否前台打开word程序,或者后台运行
318. wordBean.createNewDocument();//创建一个新文档
319. wordBean.setLocation();
320. wordBean.insertTable("表名",3,2);
321. wordBean.saveFileAs("d://table.doc");
322. wordBean.closeDocument();
323. wordBean.closeWord();
324. }
325. publicstaticvoidmergeTableCellTest(){
326. insertTableTest();//生成d://table.doc
327. WordBeanwordBean=newWordBean();
328. wordBean.setVisible(true);//是否前台打开word程序,或者后台运行
329. wordBean.openFile("d://table.doc");
330. wordBean.mergeCellTest();
331. }
332. publicstaticvoidmain(String[]args){
333. //进行测试前要保证d://a.jpg图片文件存在
334. //createANewFileTest();//创建一个新文件
335. //openAnExistsFileTest();//打开一个存在的文件
336. //insertFormatStr("格式化字符串");//对字符串进行一定的修饰
337. //insertTableTest();//创建一个表格
338. mergeTableCellTest();//对表格中的单元格进行合并
339. }
340. }
importjava.io.File;
importcom.jacob.activeX.ActiveXComponent;
importcom.jacob.com.Dispatch;
importcom.jacob.com.Variant;
classWordBean{
//代表一个word程序
privateActiveXComponentMsWordApp=null;
//代表进行处理的word文档
privateDispatchdocument=null;
publicWordBean(){
//OpenWordifwe/'venotdoneitalready
if(MsWordApp==null){
MsWordApp=newActiveXComponent("Word.Application");
}
}
//设置是否在前台打开word程序,
publicvoidsetVisible(booleanvisible){
MsWordApp.setProperty("Visible",newVariant(visible));
//这一句作用相同
//Dispatch.put(MsWordApp,"Visible",newVariant(visible));
}
//创建一个新文档
publicvoidcreateNewDocument(){
//FindtheDocumentscollectionobjectmaintainedbyWord
//documents表示word的所有文档窗口,(word是多文档应用程序)
Dispatchdocuments=Dispatch.get(MsWordApp,"Documents").toDispatch();
//CalltheAddmethodoftheDocumentscollectiontocreate
//anewdocumenttoedit
document=Dispatch.call(documents,"Add").toDispatch();
}
//打开一个存在的word文档,并用document引用引用它
publicvoidopenFile(StringwordFilePath){
//FindtheDocumentscollectionobjectmaintainedbyWord
//documents表示word的所有文档窗口,(word是多文档应用程序)
Dispatchdocuments=Dispatch.get(MsWordApp,"Documents").toDispatch();
document=Dispatch.call(documents,"Open",wordFilePath,
newVariant(true)/*是否进行转换ConfirmConversions*/,
newVariant(false)/*是否只读*/).toDispatch();
//document=Dispatch.invoke(documents,"Open",Dispatch.Method,
//newObject[]{wordFilePath,newVariant(true),
//newVariant(false)
//},newint[1]).toDispatch();
}
//向document中插入文本内容
publicvoidinsertText(StringtextToInsert){
//GetthecurrentselectionwithinWordatthemoment.
//anewdocumenthasjustbeencreatedthenthiswillbeat
//thetopofthenewdoc获得选中的内容,如果是一个新创建的文件,因里面无内容,则光标应处于文件开头处
Dispatchselection=Dispatch.get(MsWordApp,"Selection").toDispatch();
//取消选中,应该就是移动光标,否则新添加的内容会覆盖选中的内容
Dispatch.call(selection,"MoveRight",newVariant(1),newVariant(1));
//Putthespecifiedtextattheinsertionpoint
Dispatch.put(selection,"Text",textToInsert);
//取消选中,应该就是移动光标
Dispatch.call(selection,"MoveRight",newVariant(1),newVariant(1));
}
//向文档中添加一个图片,
publicvoidinsertJpeg(StringjpegFilePath){
Dispatchselection=Dispatch.get(MsWordApp,"Selection").toDispatch();
Dispatchimage=Dispatch.get(selection,"InLineShapes").toDispatch();
Dispatch.call(image,"AddPicture",jpegFilePath);
}
//段落的处理,插入格式化的文本
publicvoidinsertFormatStr(Stringtext){
DispatchwordContent=Dispatch.get(document,"Content").toDispatch();//取得word文件的内容
Dispatch.call(wordContent,"InsertAfter",text);//插入一个段落到最后
Dispatchparagraphs=Dispatch.get(wordContent,"Paragraphs")
.toDispatch();//所有段落
intparagraphCount=Dispatch.get(paragraphs,"Count").changeType(
Variant.VariantInt).getInt();//一共的段落数
//找到刚输入的段落,设置格式
DispatchlastParagraph=Dispatch.call(paragraphs,"Item",
newVariant(paragraphCount)).toDispatch();//最后一段(也就是刚插入的)
//Range对象表示文档中的一个连续范围,由一个起始字符位置和一个终止字符位置定义
DispatchlastParagraphRange=Dispatch.get(lastParagraph,"Range")
.toDispatch();
Dispatchfont=Dispatch.get(lastParagraphRange,"Font").toDispatch();
Dispatch.put(font,"Bold",newVariant(true));//设置为黑体
Dispatch.put(font,"Italic",newVariant(true));//设置为斜体
Dispatch.put(font,"Name",newVariant("宋体"));//
Dispatch.put(font,"Size",newVariant(12));//小四
Dispatchselection=Dispatch.get(MsWordApp,"Selection").toDispatch();
Dispatch.call(selection,"TypeParagraph");//插入一个空行
Dispatchalignment=Dispatch.get(selection,"ParagraphFormat")
.toDispatch();//段落格式
Dispatch.put(alignment,"Alignment","2");//(1:置中2:靠右3:靠左)
}
//word中在对表格进行遍历的时候,是先列后行先column后cell
//另外下标从1开始
publicvoidinsertTable(StringtableTitle,introw,intcolumn){
Dispatchselection=Dispatch.get(MsWordApp,"Selection").toDispatch();//输入内容需要的对象
Dispatch.call(selection,"TypeText",tableTitle);//写入标题内容//标题格行
Dispatch.call(selection,"TypeParagraph");//空一行段落
Dispatch.call(selection,"TypeParagraph");//空一行段落
Dispatch.call(selection,"MoveDown");//游标往下一行
//建立表格
Dispatchtables=Dispatch.get(document,"Tables").toDispatch();
//intcount=Dispatch.get(tables,
//"Count").changeType(Variant.VariantInt).getInt();//document中的表格数量
//Dispatchtable=Dispatch.call(tables,"Item",newVariant(
//1)).toDispatch();//文档中第一个表格
Dispatchrange=Dispatch.get(selection,"Range").toDispatch();///当前光标位置或者选中的区域
DispatchnewTable=Dispatch.call(tables,"Add",range,
newVariant(row),newVariant(column),newVariant(1))
.toDispatch();//设置row,column,表格外框宽度
Dispatchcols=Dispatch.get(newTable,"Columns").toDispatch();//此表的所有列,
intcolCount=Dispatch.get(cols,"Count").changeType(
Variant.VariantInt).getInt();//一共有多少列实际上这个数==column
System.out.println(colCount+"列");
for(inti=1;i<=colCount;i++){//循环取出每一列
Dispatchcol=Dispatch.call(cols,"Item",newVariant(i))
.toDispatch();
Dispatchcells=Dispatch.get(col,"Cells").toDispatch();//当前列中单元格
intcellCount=Dispatch.get(cells,"Count").changeType(
Variant.VariantInt).getInt();//当前列中单元格数实际上这个数等于row
for(intj=1;j<=cellCount;j++){//每一列中的单元格数
//Dispatchcell=Dispatch.call(cells,"Item",new
//Variant(j)).toDispatch();//当前单元格
//Dispatchcell=Dispatch.call(newTable,"Cell",new
//Variant(j),newVariant(i)).toDispatch();//取单元格的另一种方法
//Dispatch.call(cell,"Select");//选中当前单元格
//Dispatch.put(selection,"Text",
//"第"+j+"行,第"+i+"列");//往选中的区域中填值,也就是往当前单元格填值
putTxtToCell(newTable,j,i,"第"+j+"行,第"+i+"列");//与上面四句的作用相同
}
}
}
/***/
/**
*在指定的单元格里填写数据
*
*@paramtableIndex
*@paramcellRowIdx
*@paramcellColIdx
*@paramtxt
*/
publicvoidputTxtToCell(Dispatchtable,intcellRowIdx,intcellColIdx,
Stringtxt){
Dispatchcell=Dispatch.call(table,"Cell",newVariant(cellRowIdx),
newVariant(cellColIdx)).toDispatch();
Dispatch.call(cell,"Select");
Dispatchselection=Dispatch.get(MsWordApp,"Selection").toDispatch();//输入内容需要的对象
Dispatch.put(selection,"Text",txt);
}
/***/
/**
*在指定的单元格里填写数据
*
*@paramtableIndex
*@paramcellRowIdx
*@paramcellColIdx
*@paramtxt
*/
publicvoidputTxtToCell(inttableIndex,intcellRowIdx,intcellColIdx,
Stringtxt){
//所有表格
Dispatchtables=Dispatch.get(document,"Tables").toDispatch();
//要填充的表格
Dispatchtable=Dispatch.call(tables,"Item",newVariant(tableIndex))
.toDispatch();
Dispatchcell=Dispatch.call(table,"Cell",newVariant(cellRowIdx),
newVariant(cellColIdx)).toDispatch();
Dispatch.call(cell,"Select");
Dispatchselection=Dispatch.get(MsWordApp,"Selection").toDispatch();//输入内容需要的对象
Dispatch.put(selection,"Text",txt);
}
//合并两个单元格
publicvoidmergeCell(Dispatchcell1,Dispatchcell2){
Dispatch.call(cell1,"Merge",cell2);
}
publicvoidmergeCell(Dispatchtable,introw1,intcol1,introw2,intcol2){
Dispatchcell1=Dispatch.call(table,"Cell",newVariant(row1),
newVariant(col1)).toDispatch();
Dispatchcell2=Dispatch.call(table,"Cell",newVariant(row2),
newVariant(col2)).toDispatch();
mergeCell(cell1,cell2);
}
publicvoidmergeCellTest(){
Dispatchtables=Dispatch.get(document,"Tables").toDispatch();
inttableCount=Dispatch.get(tables,"Count").changeType(
Variant.VariantInt).getInt();//document中的表格数量
Dispatchtable=Dispatch.call(tables,"Item",newVariant(tableCount))
.toDispatch();//文档中最后一个table
mergeCell(table,1,1,1,2);//将table中x=1,y=1与x=1,y=2的两个单元格合并
}
//========================================================
/***/
/**
*把选定的内容或光标插入点向上移动
*
*@parampos
*移动的距离
*/
publicvoidmoveUp(intpos){
Dispatchselection=Dispatch.get(MsWordApp,"Selection").toDispatch();//输入内容需要的对象
for(inti=0;i<pos;i++){
//MoveDownMoveLeftmoveRight
//moveStart(Dispatch.call(selection,"HomeKey",newVariant(6));
//)
//moveEndDispatch.call(selection,"EndKey",newVariant(6));
Dispatch.call(selection,"MoveUp");
}
}
/***/
/**
*从选定内容或插入点开始查找文本
*
*@paramtoFindText
*要查找的文本
*@returnbooleantrue-查找到并选中该文本,false-未查找到文本
*/
publicbooleanfind(StringtoFindText){
if(toFindText==null||toFindText.equals(""))
returnfalse;
Dispatchselection=Dispatch.get(MsWordApp,"Selection").toDispatch();//输入内容需要的对象
//从selection所在位置开始查询
Dispatchfind=Dispatch.call(selection,"Find").toDispatch();
//设置要查找的内容
Dispatch.put(find,"Text",toFindText);
//向前查找
Dispatch.put(find,"Forward","True");
//设置格式
Dispatch.put(find,"Format","True");
//大小写匹配
Dispatch.put(find,"MatchCase","True");
//全字匹配
Dispatch.put(find,"MatchWholeWord","True");
//查找并选中
returnDispatch.call(find,"Execute").getBoolean();
}
/***/
/**
*把选定选定内容设定为替换文本
*
*@paramtoFindText
*查找字符串
*@paramnewText
*要替换的内容
*@return
*/
publicbooleanreplaceText(StringtoFindText,StringnewText){
if(!find(toFindText))
returnfalse;
Dispatchselection=Dispatch.get(MsWordApp,"Selection").toDispatch();//输入内容需要的对象
Dispatch.put(selection,"Text",newText);
returntrue;
}
publicvoidprintFile(){
//Justprintthecurrentdocumenttothedefaultprinter
Dispatch.call(document,"PrintOut");
}
//保存文档的更改
publicvoidsave(){
Dispatch.call(document,"Save");
}
publicvoidsaveFileAs(Stringfilename){
Dispatch.call(document,"SaveAs",filename);
}
publicvoidcloseDocument(){
//Closethedocumentwithoutsavingchanges
//0=wdDoNotSaveChanges
//-1=wdSaveChanges
//-2=wdPromptToSaveChanges
Dispatch.call(document,"Close",newVariant(0));
document=null;
}
publicvoidcloseWord(){
Dispatch.call(MsWordApp,"Quit");
MsWordApp=null;
document=null;
}
//设置wordApp打开后窗口的位置
publicvoidsetLocation(){
DispatchactiveWindow=Dispatch.get(MsWordApp,"Application")
.toDispatch();
Dispatch.put(activeWindow,"WindowState",newVariant(1));//0=default
//1=maximize
//2=minimize
Dispatch.put(activeWindow,"Top",newVariant(0));
Dispatch.put(activeWindow,"Left",newVariant(0));
Dispatch.put(activeWindow,"Height",newVariant(600));
Dispatch.put(activeWindow,"width",newVariant(800));
}
}
publicclassJacobTest2{
publicstaticvoidcreateANewFileTest(){
WordBeanwordBean=newWordBean();
//word.openWord(true);//打开word程序
wordBean.setVisible(true);
wordBean.createNewDocument();//创建一个新文档
wordBean.setLocation();//设置打开后窗口的位置
wordBean.insertText("你好");//向文档中插入字符
wordBean.insertJpeg("D:"+File.separator+"a.jpg");//插入图片
//如果,想保存文件,下面三句
//word.saveFileAs("d://a.doc");
//word.closeDocument();
//word.closeWord();
}
publicstaticvoidopenAnExistsFileTest(){
WordBeanwordBean=newWordBean();
wordBean.setVisible(true);//是否前台打开word程序,或者后台运行
wordBean.openFile("d://a.doc");
wordBean.insertJpeg("D:"+File.separator+"a.jpg");//插入图片(注意刚打开的word
//,光标处于开头,故,图片在最前方插入)
wordBean.save();
wordBean.closeDocument();
wordBean.closeWord();
}
publicstaticvoidinsertFormatStr(Stringstr){
WordBeanwordBean=newWordBean();
wordBean.setVisible(true);//是否前台打开word程序,或者后台运行
wordBean.createNewDocument();//创建一个新文档
wordBean.insertFormatStr(str);//插入一个段落,对其中的字体进行了设置
}
publicstaticvoidinsertTableTest(){
WordBeanwordBean=newWordBean();
wordBean.setVisible(true);//是否前台打开word程序,或者后台运行
wordBean.createNewDocument();//创建一个新文档
wordBean.setLocation();
wordBean.insertTable("表名",3,2);
wordBean.saveFileAs("d://table.doc");
wordBean.closeDocument();
wordBean.closeWord();
}
publicstaticvoidmergeTableCellTest(){
insertTableTest();//生成d://table.doc
WordBeanwordBean=newWordBean();
wordBean.setVisible(true);//是否前台打开word程序,或者后台运行
wordBean.openFile("d://table.doc");
wordBean.mergeCellTest();
}
publicstaticvoidmain(String[]args){
//进行测试前要保证d://a.jpg图片文件存在
//createANewFileTest();//创建一个新文件
//openAnExistsFileTest();//打开一个存在的文件
//insertFormatStr("格式化字符串");//对字符串进行一定的修饰
//insertTableTest();//创建一个表格
mergeTableCellTest();//对表格中的单元格进行合并
}
}
java写入word表格模板(欢迎高手过来探讨)
我有一份word表格模板,格式是规定的了
数据是从数据库读出来的,现在想把读出来的数据插入到模板的相应位置
大家有什么好建议吗??
我知道用jacod组件可以,但是jacod效率太低,大家如果有其他好的方法,麻烦提供一下,谢谢!
问题补充:
BarryWei有没有Demo呢??有的话可以发给我吗??
falcon1990是利用poi对excel表格操作,这个我也会啊,我要的是对word的表格
问题补充:
java下的该问题已经关闭:既然大家都没有什么好点的方法,我只能去操作2007的XML啦,推荐一篇文章给大家http://www.infoq.com/cn/articles/cracking-office-2007-with-java
回答
首先,在word模板中适当的位置处加上特殊标记,比如$内容$。
接着,用BufferedReader把模板中的所有字符串取出来,放入StringBuffer对象中。
第三,将StringBuffer对象中所有$内容$replace掉,换成数据库中取出的结果。
第四,done。
packagecn.com.enjoysoft.connection.db;
importjava.io.FileNotFoundException;
importjava.io.IOException;
importjava.io.OutputStream;
importjava.sql.Connection;
importjava.sql.ResultSet;
importjava.sql.SQLException;
importjava.sql.Statement;
importjava.text.SimpleDateFormat;
importjava.util.Date;
importjavax.servlet.ServletException;
importjavax.servlet.http.HttpServlet;
importjavax.servlet.http.HttpServletRequest;
importjavax.servlet.http.HttpServletResponse;
importorg.apache.poi.hssf.usermodel.HSSFCell;
importorg.apache.poi.hssf.usermodel.HSSFCellStyle;
importorg.apache.poi.hssf.usermodel.HSSFFont;
importorg.apache.poi.hssf.usermodel.HSSFRichTextString;
importorg.apache.poi.hssf.usermodel.HSSFRow;
importorg.apache.poi.hssf.usermodel.HSSFSheet;
importorg.apache.poi.hssf.usermodel.HSSFWorkbook;
importorg.apache.poi.hssf.util.HSSFColor;
@SuppressWarnings("serial")
publicclassDownExcelextendsHttpServlet{
publicvoiddoGet(HttpServletRequestrequest,HttpServletResponseresponse)
throwsServletException,IOException{
SimpleDateFormatsdf=newSimpleDateFormat("yyyy-MM-dd");
StringfileName=sdf.format(newDate())+"导出数据";
fileName=response.encodeURL(newString(fileName.getBytes("GBK"),"iso8859-1"));//转码
response.setContentType("application/octet-stream");
response.setHeader("Content-Disposition","attachement;filename="
+fileName+".xls");
Stringtype=request.getParameter("type");
try{
OutputStreamos=response.getOutputStream();
HSSFWorkbookwb=generateWorkbook(type);
if(wb!=null){
wb.write(os);
}
os.flush();
os.close();
}catch(FileNotFoundExceptione){
e.printStackTrace();
}catch(IOExceptione){
e.printStackTrace();
}
}
publicvoiddoPost(HttpServletRequestrequest,HttpServletResponseresponse)
throwsServletException,IOException{
doGet(request,response);
}
staticvoidprocessCell(HSSFCellcell,intvalue,HSSFCellStylestyle){
cell.setCellValue(value);
cell.setCellStyle(style);
}
staticvoidprocessCell(HSSFCellcell,Stringvalue,HSSFCellStylestyle){
HSSFRichTextString_value=newHSSFRichTextString(value);
cell.setCellValue(_value);
cell.setCellStyle(style);
}
privateHSSFWorkbookgenerateWorkbook(Stringtype){
Connectionconn=null;
try{
conn=TodayConnection.getConnection();
Statementstmt=conn.createStatement();
Stringsql=null;
if(type==null||type.equals("")){
sql="select*fromtelNumberorderbyiddesc";
}else{
sql="select*fromtelNumberwherecounseling='"+type+"'orderbyiddesc";
}
ResultSetrs=stmt.executeQuery(sql);
HSSFWorkbookworkbook=newHSSFWorkbook();
HSSFSheetsheet=workbook.createSheet("导出数据");
HSSFRowrow=sheet.createRow((short)0);
row.setHeight((short)(15*32));
HSSFCell[]headArray=newHSSFCell[7];
String[]headTitles=newString[]{"No.","姓名","电话","公司名称",
"咨询项目","备注","时间"};
HSSFCellStylestyle=workbook.createCellStyle();
//这里解决背景颜色
style.setFillForegroundColor(HSSFColor.GREY_25_PERCENT.index);
style.setFillPattern(HSSFCellStyle.SOLID_FOREGROUND);
style.setBorderBottom(HSSFCellStyle.BORDER_THIN);
style.setBottomBorderColor(HSSFColor.BLACK.index);
style.setBorderLeft(HSSFCellStyle.BORDER_THIN);
style.setLeftBorderColor(HSSFColor.BLACK.index);
style.setBorderRight(HSSFCellStyle.BORDER_THIN);
style.setRightBorderColor(HSSFColor.BLACK.index);
style.setBorderTop(HSSFCellStyle.BORDER_THIN);
style.setTopBorderColor(HSSFColor.BLACK.index);
style.setAlignment(HSSFCellStyle.ALIGN_CENTER);
//字体
HSSFFontfont=workbook.createFont();
font.setFontHeightInPoints((short)12);
font.setFontName("CourierNew");
font.setBoldweight(HSSFFont.BOLDWEIGHT_BOLD);
style.setFont(font);
for(inti=0;i<headArray.length;i++){
headArray[i]=row.createCell(i);
headArray[i].setCellStyle(style);
HSSFRichTextStringvalue=newHSSFRichTextString(headTitles[i]);
headArray[i].setCellValue(value);
}
HSSFCellStylestyleData=workbook.createCellStyle();
styleData.setBorderBottom(HSSFCellStyle.BORDER_THIN);
styleData.setBottomBorderColor(HSSFColor.BLACK.index);
styleData.setBorderLeft(HSSFCellStyle.BORDER_THIN);
styleData.setLeftBorderColor(HSSFColor.BLACK.index);
styleData.setBorderRight(HSSFCellStyle.BORDER_THIN);
styleData.setRightBorderColor(HSSFColor.BLACK.index);
styleData.setBorderTop(HSSFCellStyle.BORDER_THIN);
styleData.setTopBorderColor(HSSFColor.BLACK.index);
styleData.setAlignment(HSSFCellStyle.ALIGN_CENTER);
//字体
HSSFFontfont1=workbook.createFont();
font1.setFontHeightInPoints((short)12);
font1.setFontName("CourierNew");
styleData.setFont(font1);
//循环查询的所有记录把每一行写入worksheet里面
intno=1;
shortrowNo=1;
while(rs.next()){
HSSFRowdataRow=sheet.createRow(rowNo++);
dataRow.setHeight((short)(12*32));
processCell(dataRow.createCell(0),no++,styleData);
processCell(dataRow.createCell(1),rs.getString("name"),
styleData);
processCell(dataRow.createCell(2),rs.getString("telNumber"),
styleData);
processCell(dataRow.createCell(3),rs.getString("corp"),
styleData);
processCell(dataRow.createCell(4),rs.getString("counseling"),
styleData);
processCell(dataRow.createCell(5),rs.getString("remark"),
styleData);
processCell(dataRow.createCell(6),rs.getString("jointime"),
styleData);
}
//调整宽度
short[]widths=newshort[]{5,15,18,22,13,50,30};
for(shortk=0;k<7;k++){
sheet.setColumnWidth(k,widths[k]*256);
}
returnworkbook;
}catch(Exceptione){
}finally{
try{
//关闭数据库连接
if(conn!=null&&!conn.isClosed())
conn.close();
}catch(SQLExceptione){
}
}//ENDOFPROGRAMM
returnnull;
}
}
这里是详细的代码!需要poi-3.2-FINAL-20081019.jar自己下就可以了!
如果是jsp页面的话,那么生成word很简单的,我以前做的那个系统最后就有个报表要提供下载和打印,都要求是word文档,我的解决方法:
1、做好一个table布局的jsp页面,在里面添好表名、表头,样式等
2、在servlet或者action中调用biz读取数据,然后写入session或者request中
3、转向到jsp页面,在页面中读取session或者request中的数据
4、要注意的是,这个jsp页面不是一般的页面,这个jsp页面的content-type要设置,改成这样:
<metahttp-equiv="Content-Type"content="application/msword;charset=gb2312"/>
这样就可以提供word格式的文档,而且会在客户端提供下载。
你要客户直接把做好的word下载下来就ok,稍微编辑一些字体大小或者样式(或者这些东西在jsp页面中全部做好),直接打印或者备案就ok。
希望对你有用。