Всем привет.
Собственно, есть класс который заменяет текст в .doc'е. Проблема в том, что слетают стили (центрирование текста, размер шрифта и т.д.). Бьюсь уже два дня, может кто поможет?
Заранее спасибо!
1.
2.
3.
4.
5.
6.
7.
8.
9.
10.
11.
12.
13.
14.
15.
16.
17.
18.
19.
20.
21.
22.
23.
24.
25.
26.
27.
28.
29.
30.
31.
32.
33.
34.
35.
36.
37.
38.
39.
40.
41.
42.
43.
44.
45.
46.
47.
48.
49.
50.
51.
52.
53.
54.
55.
56.
57.
58.
59.
60.
61.
62.
63.
64.
65.
66.
67.
68.
69.
70.
71.
72.
73.
74.
75.
76.
77.
78.
79.
80.
81.
82.
83.
84.
85.
86.
87.
88.
89.
90.
91.
92.
93.
94.
95.
96.
97.
public class CreateWordDoc {
public static void editDoc(HttpServletResponse response) throws IOException{
ArrayList<String[]> info = new ArrayList<String[]>();
info.add(new String[]{"xxx", "XXX"});
info.add(new String[]{"yyy", "YYY"});
info.add(new String[]{"zzz", "ZZZ"});
POIFSFileSystem fs = null;
try {
FileInputStream stream=new FileInputStream("D:\\1.doc");
HWPFDocument doc = new HWPFDocument(stream);
Range range = doc.getRange();
CharacterRun run = range.insertAfter("");
run.setBold(true);
run.setItalic(true);
run.setCapitalized(true);
for (int i = 0; i < info.size(); i++) {
String[] array = info.get(i);
String template = array[0];
String value = array[1];
if (template.length() > value.length()) {
while (template.length() > value.length()) {
value = value + " ";
}
}
doc = replaceText(doc, template, value);
}
saveWord(doc, response);
}
catch(FileNotFoundException e){
e.printStackTrace();
}
catch(IOException e){
e.printStackTrace();
}
}
private static HWPFDocument replaceText(HWPFDocument doc, String findText, String replaceText){
Range r1 = doc.getRange();
CharacterRun run1 = r1.insertAfter("");
run1.setBold(true);
run1.setItalic(true);
run1.setCapitalized(true);
for (int i = 0; i < r1.numSections(); ++i ) {
Section s = r1.getSection(i);
for (int x = 0; x < s.numParagraphs(); x++) {
Paragraph p = s.getParagraph(x);
for (int z = 0; z < p.numCharacterRuns(); z++) {
CharacterRun run = p.getCharacterRun(z);
String text = run.text();
if(text.contains(findText)) {
run.replaceText(findText, replaceText);
}
}
}
}
return doc;
}
private static void saveWord(HWPFDocument doc, HttpServletResponse response) throws FileNotFoundException, IOException{
FileOutputStream out = null;
try{
String filename = "new.doc";
ServletOutputStream outStream = response.getOutputStream();
response.setContentType("application/octet-stream");
response.setHeader("Content-Disposition", "attachment; filename=\""
+ filename + "\"");
ByteArrayOutputStream baos = new ByteArrayOutputStream();
doc.write(baos);
byte[] result = baos.toByteArray();
int length = 0;
byte[] byteBuffer = new byte[1024];
DataInputStream in = new DataInputStream(new ByteArrayInputStream(
result));
while ((in != null) && ((length = in.read(byteBuffer)) != -1)) {
outStream.write(byteBuffer, 0, length);
}
in.close();
outStream.close();
}
catch (Exception e) {
e.printStackTrace();
}
}
}