官网:http://www.xdocin.com

Controller层:

  1. //创建对象
  2. XDocService xdocService = new XDocService();
  3. //封装参数
  4. Map<String, Object> param = new HashMap<String, Object>();
  5. param.put("socre", "S,2012,2013,2014,2015\r\nA,233,127,135,117\r\nB,165,190,148,280\r\nC,235,165,174,219\r\nD,250,195,145,246\r\nE,215,216,184,122");
  6. param.put("user", user.getUserName());
  7.  
  8. String fileName = user.getUserName()+"_考试统计.docx";
  9. file = new File(CommonConstants.fileRoot+"/static/exam/"+fileName);
  10. xdocService.run( CommonConstants.fileRoot+"/static/exam/个人成绩统计模板.docx",param,file);

Controller层:

XDocService工具类

  1. import org.w3c.dom.Document;
  2. import org.w3c.dom.Element;
  3. import org.w3c.dom.NamedNodeMap;
  4. import org.w3c.dom.NodeList;
  5. import org.xml.sax.SAXException;
  6.  
  7. import javax.xml.parsers.DocumentBuilder;
  8. import javax.xml.parsers.DocumentBuilderFactory;
  9. import javax.xml.parsers.ParserConfigurationException;
  10. import java.beans.BeanInfo;
  11. import java.beans.Introspector;
  12. import java.beans.PropertyDescriptor;
  13. import java.io.*;
  14. import java.lang.annotation.*;
  15. import java.lang.reflect.Array;
  16. import java.lang.reflect.Field;
  17. import java.lang.reflect.Method;
  18. import java.net.*;
  19. import java.text.SimpleDateFormat;
  20. import java.util.*;
  21.  
  22. /**
  23. * XDoc服务
  24. *
  25. * @author xdoc
  26. * @version 11.4.2
  27. */
  28. public class XDocService {
  29. /**
  30. * 默认服务器地址
  31. */
  32. public static String DEFAULT_URL = "http://www.xdocin.com";
  33. /**
  34. * 默认账号口令
  35. */
  36. public static String DEFAULT_KEY = "";
  37. private String url;
  38. private String key;
  39.  
  40. /**
  41. * 服务地址
  42. *
  43. * @return
  44. */
  45. public String getUrl() {
  46. return url;
  47. }
  48.  
  49. /**
  50. * 服务地址
  51. *
  52. * @param url
  53. */
  54. public void setUrl(String url) {
  55. this.url = url;
  56. }
  57.  
  58. /**
  59. * 账号口令
  60. *
  61. * @return
  62. */
  63. public String getKey() {
  64. return key;
  65. }
  66.  
  67. /**
  68. * 账号口令
  69. *
  70. * @param key
  71. */
  72. public void setKey(String key) {
  73. this.key = key;
  74. }
  75.  
  76. /**
  77. * 构造器
  78. */
  79. public XDocService() {
  80. this(DEFAULT_URL, DEFAULT_KEY);
  81. }
  82.  
  83. /**
  84. * 构造器
  85. *
  86. * @param url 服务地址
  87. */
  88. public XDocService(String url) {
  89. this(url, DEFAULT_KEY);
  90. }
  91.  
  92. /**
  93. * 构造器
  94. *
  95. * @param url 服务地址
  96. * @param key 账号
  97. */
  98. public XDocService(String url, String key) {
  99. this.url = url;
  100. this.key = key;
  101. }
  102.  
  103. /**
  104. * 转换为其它格式文件
  105. *
  106. * @param xdoc xdoc
  107. * @param file 其它格式文件,如:a.pdf
  108. * @throws IOException
  109. */
  110. public void to(File xdoc, File file) throws IOException {
  111. to(xdoc.getAbsolutePath(), file);
  112. }
  113.  
  114. /**
  115. * 转换为其它格式文件
  116. *
  117. * @param xdoc xdoc文本<br>
  118. * URL:文档URL地址,格式支持:xdoc、json、docx、epub、txt、rtf等,支持datauri协议,可传递二进制数据,支持本地文件<br>
  119. * 纯文本:以"text:"开头的文本<br>
  120. * JSON:符合XDOC-JSON规范的JSON文本<br>
  121. * XML:符合XDOC-XML规范的XML文本<br>
  122. * HTML:用html标签括起来的html文本,如:&lt;html&gt;&lt;h1&gt;Hello&lt;/h1&gt;&lt;/html&gt;
  123. * @param file 其它格式文件,如:a.pdf
  124. * @throws IOException
  125. */
  126. public void to(String xdoc, File file) throws IOException {
  127. to(xdoc, new FileOutputStream(file), getFormat(file.getName()));
  128. }
  129.  
  130. /**
  131. * 转换为其它格式,保存到指定流中
  132. *
  133. * @param xdoc xdoc
  134. * @param out 输出目标,OutputStream或HttpServletResponse
  135. * @param format format
  136. * @throws IOException
  137. */
  138. public void to(String xdoc, Object out, String format) throws IOException {
  139. Map<String, Object> param = new HashMap<String, Object>();
  140. param.put("_func", "to");
  141. param.put("_xdoc", xdoc);
  142. param.put("_format", format);
  143. invoke(checkParam(param), out);
  144. }
  145.  
  146. /**
  147. * 转换为其它格式并发送
  148. *
  149. * @param xdoc xdoc
  150. * @param to 目标,支持ftp、http、mail、datauri等
  151. * @param format format
  152. * @throws IOException
  153. */
  154. public String to(String xdoc, String to, String format) throws IOException {
  155. Map<String, Object> param = new HashMap<String, Object>();
  156. param.put("_func", "to");
  157. param.put("_xdoc", xdoc);
  158. param.put("_to", to);
  159. param.put("_format", format);
  160. ByteArrayOutputStream out = new ByteArrayOutputStream();
  161. invoke(checkParam(param), out);
  162. return new String(out.toByteArray(), "UTF-8");
  163. }
  164.  
  165. /**
  166. * 运行xdoc
  167. *
  168. * @param xdoc xdoc
  169. * @param param 参数
  170. * @param file 目标文件
  171. * @throws IOException
  172. */
  173. public void run(File xdoc, Map<String, Object> param, File file) throws IOException {
  174. if (!param.containsKey("_xformat")) {
  175. param.put("_xformat", getFormat(file.getName()));
  176. }
  177. run(xdoc.getAbsolutePath(), param, file);
  178. }
  179.  
  180. /**
  181. * 运行xdoc
  182. *
  183. * @param xdoc xdoc
  184. * @param param 参数
  185. * @param file 目标文件
  186. * @throws IOException
  187. */
  188. public void run(String xdoc, Map<String, Object> param, File file) throws IOException {
  189. run(xdoc, param, new FileOutputStream(file), getFormat(file.getName()));
  190. }
  191.  
  192. /**
  193. * 运行xdoc
  194. *
  195. * @param xdoc xdoc
  196. * @param param 参数
  197. * @param out 输出目标,OutputStream或HttpServletResponse
  198. * @param format 目标格式
  199. * @throws IOException
  200. */
  201. public void run(String xdoc, Map<String, Object> param, Object out, String format) throws IOException {
  202. param.put("_func", "run");
  203. param.put("_xdoc", xdoc);
  204. param.put("_format", format);
  205. invoke(checkParam(param), out);
  206. }
  207.  
  208. /**
  209. * 运行xdoc并发送
  210. *
  211. * @param xdoc xdoc
  212. * @param param 参数
  213. * @param to 目标,支持ftp、http、mail、datauri等
  214. * @param format 目标格式
  215. * @throws IOException
  216. */
  217. public String run(String xdoc, Map<String, Object> param, String to, String format) throws IOException {
  218. param.put("_func", "run");
  219. param.put("_xdoc", xdoc);
  220. param.put("_to", to);
  221. param.put("_format", format);
  222. ByteArrayOutputStream out = new ByteArrayOutputStream();
  223. invoke(checkParam(param), out);
  224. return new String(out.toByteArray(), "UTF-8");
  225. }
  226.  
  227. /**
  228. * 运行注解XDoc
  229. *
  230. * @param obj
  231. * @param file
  232. * @throws IOException
  233. */
  234. public void run(Object obj, File file) throws IOException {
  235. run(obj, new FileOutputStream(file), getFormat(file.getName()));
  236. }
  237.  
  238. /**
  239. * 运行注解XDoc
  240. *
  241. * @param obj
  242. * @param out 目标流
  243. * @param format 目标格式
  244. * @throws IOException
  245. */
  246. public void run(Object obj, Object out, String format) throws IOException {
  247. run(obj, out, null, format);
  248. }
  249.  
  250. /**
  251. * 运行注解XDoc
  252. *
  253. * @param obj
  254. * @param to 目标,支持ftp、http、mail、datauri等
  255. * @param format 目标格式
  256. * @throws IOException
  257. */
  258. public void run(Object obj, String to, String format) throws IOException {
  259. run(obj, null, to, format);
  260. }
  261.  
  262. private void run(Object obj, Object out, String to, String format) throws IOException {
  263. String xurl = "";
  264. XDoc xdoc = obj.getClass().getAnnotation(XDoc.class);
  265. if (xdoc != null) {
  266. xurl = xdoc.value();
  267. }
  268. if (xurl.length() == 0) {
  269. xurl = "./" + obj.getClass().getSimpleName() + ".xdoc";
  270. }
  271. Field[] fields = obj.getClass().getDeclaredFields();
  272. boolean hasXParam = false;
  273. XParam xParam;
  274. Map<String, Object> param = new HashMap<String, Object>();
  275. String name;
  276. Object value;
  277. for (Field field : fields) {
  278. xParam = field.getAnnotation(XParam.class);
  279. if (xParam != null) {
  280. hasXParam = true;
  281. name = xParam.value();
  282. if (name.length() == 0) {
  283. name = field.getName();
  284. }
  285. try {
  286. field.setAccessible(true);
  287. value = field.get(obj);
  288. if (name.equals("_xdoc")) {
  289. xurl = String.valueOf(value);
  290. } else {
  291. param.put(name, value);
  292. }
  293. } catch (Exception e) {
  294. throw new IOException(e);
  295. }
  296. }
  297. }
  298. if (!hasXParam) { //没有指定xparam,传入所有属性
  299. for (Field field : fields) {
  300. try {
  301. field.setAccessible(true);
  302. param.put(field.getName(), field.get(obj));
  303. } catch (Exception e) {
  304. throw new IOException(e);
  305. }
  306. }
  307. }
  308. if (out != null) {
  309. this.run(xurl, param, out, format);
  310. } else {
  311. this.run(xurl, param, to, format);
  312. }
  313. }
  314.  
  315. /**
  316. * 招呼
  317. *
  318. * @return
  319. * @throws IOException
  320. */
  321. public boolean hi() throws IOException {
  322. return invokeStringFunc("hi").equals("ok");
  323. }
  324.  
  325. /**
  326. * 关于
  327. */
  328. public String about() throws IOException {
  329. return invokeStringFunc("about");
  330. }
  331.  
  332. /**
  333. * 动态口令
  334. *
  335. * @return
  336. * @throws IOException
  337. */
  338. public String dkey() throws IOException {
  339. return invokeStringFunc("dkey");
  340. }
  341.  
  342. /**
  343. * 修改口令
  344. *
  345. * @return
  346. * @throws IOException
  347. */
  348. public String ckey() throws IOException {
  349. return invokeStringFunc("ckey");
  350. }
  351.  
  352. /**
  353. * 注册
  354. *
  355. * @param mail 邮件
  356. * @return
  357. * @throws IOException
  358. */
  359. public String reg(String mail) throws IOException {
  360. Map<String, String> params = new HashMap<String, String>();
  361. params.put("_func", "reg");
  362. params.put("_mail", mail);
  363. ByteArrayOutputStream out = new ByteArrayOutputStream();
  364. invoke(params, out);
  365. return (String) parse(out.toByteArray());
  366. }
  367.  
  368. /**
  369. * 账户信息
  370. *
  371. * @return
  372. * @throws IOException
  373. */
  374. @SuppressWarnings("unchecked")
  375. public Map<String, String> acc() throws IOException {
  376. Map<String, String> params = new HashMap<String, String>();
  377. params.put("_func", "acc");
  378. ByteArrayOutputStream out = new ByteArrayOutputStream();
  379. invoke(params, out);
  380. return (Map<String, String>) parse(out.toByteArray());
  381. }
  382.  
  383. /**
  384. * 基于ID上传
  385. *
  386. * @param id
  387. * @param file
  388. * @return
  389. * @throws IOException
  390. */
  391. public void sup(String id, File file) throws IOException {
  392. sup(id, toDataURI(file.getAbsolutePath()));
  393. }
  394.  
  395. /**
  396. * 基于ID上传
  397. *
  398. * @param id
  399. * @param in
  400. * @throws IOException
  401. */
  402. public void sup(String id, InputStream in) throws IOException {
  403. sup(id, toDataURI(in));
  404. }
  405.  
  406. private void sup(String id, String dataUri) throws IOException {
  407. Map<String, String> params = new HashMap<String, String>();
  408. params.put("_func", "sup");
  409. params.put("_id", id);
  410. params.put("_data", dataUri);
  411. ByteArrayOutputStream out = new ByteArrayOutputStream();
  412. invoke(params, out);
  413. parse(out.toByteArray());
  414. }
  415.  
  416. /**
  417. * 基于ID下载
  418. *
  419. * @param id
  420. * @param file
  421. * @throws IOException
  422. */
  423. public void sdown(String id, File file) throws IOException {
  424. sdown(id, new FileOutputStream(file));
  425. }
  426.  
  427. /**
  428. * 基于ID下载
  429. *
  430. * @param id
  431. * @param out 输出目标,OutputStream或HttpServletResponse
  432. * @throws IOException
  433. */
  434. public void sdown(String id, Object out) throws IOException {
  435. Map<String, String> params = new HashMap<String, String>();
  436. params.put("_func", "sdown");
  437. params.put("_id", id);
  438. invoke(params, out);
  439. }
  440.  
  441. /**
  442. * 基于ID删除
  443. *
  444. * @param id
  445. * @return
  446. * @throws IOException
  447. */
  448. public boolean sremove(String id) throws IOException {
  449. Map<String, String> params = new HashMap<String, String>();
  450. params.put("_func", "sremove");
  451. params.put("_id", id);
  452. ByteArrayOutputStream out = new ByteArrayOutputStream();
  453. invoke(params, out);
  454. return parse(out.toByteArray()).equals("ok");
  455. }
  456.  
  457. /**
  458. * 创建目录
  459. *
  460. * @param dir
  461. * @return
  462. * @throws IOException
  463. */
  464. public boolean mkdir(String dir) throws IOException {
  465. Map<String, String> params = new HashMap<String, String>();
  466. params.put("_func", "mkdir");
  467. params.put("_dir", dir);
  468. ByteArrayOutputStream out = new ByteArrayOutputStream();
  469. invoke(params, out);
  470. return parse(out.toByteArray()).equals("ok");
  471. }
  472.  
  473. /**
  474. * 目录列表
  475. *
  476. * @param dir
  477. * @return
  478. * @throws IOException
  479. */
  480. @SuppressWarnings("unchecked")
  481. public List<Map<String, String>> dirlist(String dir) throws IOException {
  482. Map<String, String> params = new HashMap<String, String>();
  483. params.put("_func", "dirlist");
  484. params.put("_dir", dir);
  485. ByteArrayOutputStream out = new ByteArrayOutputStream();
  486. invoke(params, out);
  487. return (List<Map<String, String>>) parse(out.toByteArray());
  488. }
  489.  
  490. /**
  491. * 文件列表
  492. *
  493. * @param dir
  494. * @return
  495. * @throws IOException
  496. */
  497. @SuppressWarnings("unchecked")
  498. public List<Map<String, String>> filelist(String dir) throws IOException {
  499. Map<String, String> params = new HashMap<String, String>();
  500. params.put("_func", "filelist");
  501. params.put("_dir", dir);
  502. ByteArrayOutputStream out = new ByteArrayOutputStream();
  503. invoke(params, out);
  504. return (List<Map<String, String>>) parse(out.toByteArray());
  505. }
  506.  
  507. /**
  508. * 上传
  509. *
  510. * @param dir
  511. * @param file
  512. * @return
  513. * @throws IOException
  514. */
  515. public void up(String dir, File file) throws IOException {
  516. up(dir, toDataURI(file.getAbsolutePath()));
  517. }
  518.  
  519. /**
  520. * 上传
  521. *
  522. * @param dir
  523. * @param in
  524. * @throws IOException
  525. */
  526. public void up(String dir, InputStream in) throws IOException {
  527. up(dir, toDataURI(in));
  528. }
  529.  
  530. private void up(String dir, String dataUri) throws IOException {
  531. Map<String, String> params = new HashMap<String, String>();
  532. params.put("_func", "up");
  533. params.put("_dir", dir);
  534. params.put("_data", dataUri);
  535. ByteArrayOutputStream out = new ByteArrayOutputStream();
  536. invoke(params, out);
  537. parse(out.toByteArray());
  538. }
  539.  
  540. /**
  541. * 下载
  542. *
  543. * @param dir
  544. * @param file
  545. * @throws IOException
  546. */
  547. public void down(String dir, File file) throws IOException {
  548. down(dir, new FileOutputStream(file));
  549. }
  550.  
  551. /**
  552. * 下载
  553. *
  554. * @param dir
  555. * @param out 输出目标,OutputStream或HttpServletResponse
  556. * @throws IOException
  557. */
  558. public void down(String dir, Object out) throws IOException {
  559. Map<String, String> params = new HashMap<String, String>();
  560. params.put("_func", "down");
  561. params.put("_dir", dir);
  562. invoke(params, out);
  563. }
  564.  
  565. /**
  566. * 删除
  567. *
  568. * @param dir
  569. * @return
  570. * @throws IOException
  571. */
  572. public boolean remove(String dir) throws IOException {
  573. Map<String, String> params = new HashMap<String, String>();
  574. params.put("_func", "remove");
  575. params.put("_dir", dir);
  576. ByteArrayOutputStream out = new ByteArrayOutputStream();
  577. invoke(params, out);
  578. return parse(out.toByteArray()).equals("ok");
  579. }
  580.  
  581. /**
  582. * 文件是否存在
  583. *
  584. * @param dir
  585. * @return
  586. * @throws IOException
  587. */
  588. public boolean exists(String dir) throws IOException {
  589. Map<String, String> params = new HashMap<String, String>();
  590. params.put("_func", "exists");
  591. params.put("_dir", dir);
  592. ByteArrayOutputStream out = new ByteArrayOutputStream();
  593. invoke(params, out);
  594. return parse(out.toByteArray()).equals("true");
  595. }
  596.  
  597. /**
  598. * 数据查询
  599. *
  600. * @param sql SQL
  601. * @return
  602. * @throws IOException
  603. */
  604. @SuppressWarnings("unchecked")
  605. public List<Map<String, String>> query(String sql) throws IOException {
  606. Map<String, String> params = new HashMap<String, String>();
  607. params.put("_func", "query");
  608. params.put("_sql", sql);
  609. ByteArrayOutputStream out = new ByteArrayOutputStream();
  610. invoke(params, out);
  611. return (List<Map<String, String>>) parse(out.toByteArray());
  612. }
  613.  
  614. /**
  615. * 基于ID的XDATA转换
  616. *
  617. * @param id
  618. * @param format 目标格式:xml、json、csv
  619. * @return
  620. * @throws IOException
  621. */
  622. public String xdataById(String id, String format) throws IOException {
  623. Map<String, String> params = new HashMap<String, String>();
  624. params.put("_func", "xdata");
  625. params.put("_id", id);
  626. params.put("_format", format);
  627. ByteArrayOutputStream out = new ByteArrayOutputStream();
  628. invoke(params, out);
  629. return (String) parse(out.toByteArray());
  630. }
  631.  
  632. /**
  633. * XDATA转换
  634. *
  635. * @param data xdata数据,格式:xml、json、csv
  636. * @param format 目标格式:xml、json、csv
  637. * @return
  638. * @throws IOException
  639. */
  640. public String xdata(String xdata, String format) throws IOException {
  641. Map<String, String> params = new HashMap<String, String>();
  642. params.put("_func", "xdata");
  643. params.put("_xdata", xdata);
  644. params.put("_format", format);
  645. ByteArrayOutputStream out = new ByteArrayOutputStream();
  646. invoke(params, out);
  647. return (String) parse(out.toByteArray());
  648. }
  649.  
  650. /**
  651. * 通过url地址调用服务,支持本地文件xdoc和xdata
  652. *
  653. * @param args
  654. */
  655. public static void main(String[] args) {
  656. if (args.length > 0 && args[0].length() > 0) {
  657. String url = args[0];
  658. if (url.charAt(0) == '@') { //命令文件
  659. File cmdFile = new File(url.substring(1));
  660. try {
  661. FileReader reader = new FileReader(cmdFile);
  662. url = (new BufferedReader(reader)).readLine();
  663. reader.close();
  664. cmdFile.delete();
  665. } catch (Exception e) {
  666. e.printStackTrace();
  667. return;
  668. }
  669. }
  670. String server = DEFAULT_URL;
  671. int pos = url.indexOf('?');
  672. if (pos > 0) {
  673. server = url.substring(0, pos);
  674. if (server.endsWith("/xdoc")) {
  675. server = server.substring(0, server.length() - 5);
  676. }
  677. url = url.substring(pos + 1);
  678. }
  679. String xkey = "";
  680. try {
  681. String[] params = url.split("&");
  682. Map<String, String> map = new HashMap<String, String>();
  683. String key, value;
  684. String to = null;
  685. for (int i = 0; i < params.length; i++) {
  686. pos = params[i].indexOf('=');
  687. if (pos > 0) {
  688. key = decode(params[i].substring(0, pos));
  689. value = decode(params[i].substring(pos + 1));
  690. if (isXDocData(key, value)) {
  691. value = toDataURI(value);
  692. } else if (key.indexOf("@file") > 0) {
  693. key = key.substring(0, key.length() - 5);
  694. value = toDataURI(value);
  695. } else if (key.equals("_key")) {
  696. xkey = value;
  697. continue;
  698. } else if (key.equals("_to") && isFile(value)) {
  699. to = value;
  700. continue;
  701. }
  702. map.put(key, value);
  703. }
  704. }
  705. if (!map.containsKey("_format") && to != null && to.indexOf('.') > 0) {
  706. map.put("_format", to.substring(to.lastIndexOf('.') + 1));
  707. }
  708. XDocService client = new XDocService(server, xkey);
  709. OutputStream out;
  710. if (to != null) {
  711. out = new FileOutputStream(to);
  712. } else {
  713. out = System.out;
  714. }
  715. client.invoke(map, out);
  716. if (to != null) {
  717. out.flush();
  718. out.close();
  719. System.out.println(">> " + to);
  720. }
  721. } catch (Exception e) {
  722. e.printStackTrace();
  723. }
  724. }
  725. }
  726.  
  727. private void invoke(Map<String, String> param, Object out) throws IOException {
  728. String xurl = this.url + (this.url.endsWith("/") ? "xdoc" : "/xdoc");
  729. HttpURLConnection httpConn = (HttpURLConnection) new URL(xurl).openConnection();
  730. httpConn.setDoOutput(true);
  731. OutputStream reqOut = httpConn.getOutputStream();
  732. reqOut.write(("&_key=").getBytes());
  733. reqOut.write(encode(this.key).getBytes());
  734. Iterator<String> it = param.keySet().iterator();
  735. String key;
  736. while (it.hasNext()) {
  737. key = it.next();
  738. reqOut.write(("&" + encode(key) + "=").getBytes());
  739. reqOut.write(encode(param.get(key)).getBytes());
  740. }
  741. reqOut.flush();
  742. reqOut.close();
  743. OutputStream os = null;
  744. if (out instanceof OutputStream) {
  745. os = (OutputStream) out;
  746. } else {
  747. try {
  748. Method method = out.getClass().getMethod("getOutputStream");
  749. os = (OutputStream) method.invoke(out);
  750. method = out.getClass().getMethod("setHeader", String.class, String.class);
  751. String[] headerNames = new String[]{"Content-Type", "Content-Disposition"};
  752. String headerValue;
  753. for (String headerName : headerNames) {
  754. headerValue = httpConn.getHeaderField(headerName);
  755. if (headerValue != null) {
  756. method.invoke(out, headerName, headerValue);
  757. }
  758. }
  759. } catch (Exception e) {
  760. throw new IOException(e);
  761. }
  762. }
  763. pipe(httpConn.getInputStream(), os);
  764. }
  765.  
  766. private Object parse(byte[] data) throws IOException {
  767. DocumentBuilderFactory factory = DocumentBuilderFactory.newInstance();
  768. factory.setValidating(false);
  769. try {
  770. DocumentBuilder builder = factory.newDocumentBuilder();
  771. Document document = builder.parse(new ByteArrayInputStream(data));
  772. document.getDocumentElement().normalize();
  773. Element root = document.getDocumentElement();
  774. if (root.getAttribute("success").equals("true")) {
  775. Element result = (Element) root.getElementsByTagName("result").item(0);
  776. String dataType = result.getAttribute("dataType");
  777. if (dataType.equals("string")) {
  778. return result.getTextContent();
  779. } else if (dataType.equals("map")) {
  780. NodeList items = result.getElementsByTagName("value");
  781. Map<String, String> map = new HashMap<String, String>();
  782. Element value;
  783. NamedNodeMap atts;
  784. for (int i = 0; i < items.getLength(); i++) {
  785. value = (Element) items.item(i);
  786. atts = value.getAttributes();
  787. for (int j = 0; j < atts.getLength(); j++) {
  788. map.put(atts.item(j).getNodeName(), atts.item(j).getNodeValue());
  789. }
  790. }
  791. return map;
  792. } else if (dataType.equals("rowset")) {
  793. Map<String, String> fieldMap = new HashMap<String, String>();
  794. String[] fields = result.getAttribute("fields").split(",");
  795. String[] formerFields = fields;
  796. if (result.hasAttribute("formerFields")) {
  797. formerFields = csvSplit(result.getAttribute("formerFields"));
  798. }
  799. for (int j = 0; j < formerFields.length; j++) {
  800. fieldMap.put(fields[j], formerFields[j]);
  801. }
  802. NodeList eleList = result.getElementsByTagName("row");
  803. Element ele;
  804. Map<String, String> map;
  805. List<Map<String, String>> List = new ArrayList<Map<String, String>>();
  806. for (int i = 0; i < eleList.getLength(); i++) {
  807. ele = (Element) eleList.item(i);
  808. map = new HashMap<String, String>();
  809. List.add(map);
  810. for (int j = 0; j < fields.length; j++) {
  811. map.put(formerFields[j], ele.getAttribute(fields[j]));
  812. }
  813. }
  814. return List;
  815. } else {
  816. return "";
  817. }
  818. } else {
  819. throw new IOException(root.getElementsByTagName("error").item(0).getTextContent());
  820. }
  821. } catch (ParserConfigurationException e) {
  822. throw new IOException(e);
  823. } catch (SAXException e) {
  824. throw new IOException(e);
  825. }
  826. }
  827.  
  828. private String invokeStringFunc(String func) throws IOException {
  829. Map<String, String> params = new HashMap<String, String>();
  830. params.put("_func", func);
  831. ByteArrayOutputStream out = new ByteArrayOutputStream();
  832. invoke(params, out);
  833. return (String) parse(out.toByteArray());
  834. }
  835.  
  836. private Map<String, String> checkParam(Map<String, Object> param) throws IOException {
  837. Map<String, String> map = new HashMap<String, String>();
  838. String key, value;
  839. Iterator<String> it = param.keySet().iterator();
  840. while (it.hasNext()) {
  841. key = it.next();
  842. value = toParamString(param.get(key));
  843. if (isXDocData(key, value)) {
  844. value = toDataURI(value);
  845. } else if (key.endsWith("@file")) {
  846. key = key.substring(0, key.length() - 5);
  847. value = toDataURI(value);
  848. }
  849. map.put(key, value);
  850. }
  851. return map;
  852. }
  853.  
  854. private static String toParamString(Object obj) throws IOException {
  855. String str;
  856. if (obj == null) {
  857. str = "";
  858. } else if (obj.getClass().isPrimitive()
  859. || obj instanceof Boolean
  860. || obj instanceof Number
  861. || obj instanceof CharSequence) {
  862. str = obj.toString();
  863. } else if (obj instanceof Date) {
  864. str = new SimpleDateFormat("yyyy-MM-dd HH:mm:ss").format((Date) obj);
  865. } else if (obj instanceof File) {
  866. str = toDataURI(((File) obj).getAbsolutePath());
  867. } else if (obj instanceof InputStream) {
  868. str = toDataURI((InputStream) obj);
  869. } else {
  870. StringBuilder sb = new StringBuilder();
  871. Set<Object> chainSet = new HashSet<Object>();
  872. writeParamString(sb, obj, chainSet);
  873. str = sb.toString();
  874. }
  875. return str;
  876. }
  877.  
  878. private static void writeParamString(StringBuilder sb, Object obj, Set<Object> set) throws IOException {
  879. if (obj == null) {
  880. sb.append("null");
  881. } else if (obj.getClass().isPrimitive()
  882. || obj instanceof Boolean
  883. || obj instanceof Number) {
  884. sb.append(toParamString(obj));
  885. } else if (obj instanceof CharSequence
  886. || obj instanceof Date) {
  887. jencode(toParamString(obj), sb);
  888. } else if (obj instanceof Collection) {
  889. sb.append("[");
  890. boolean b = false;
  891. Iterator<?> it = ((Collection<?>) obj).iterator();
  892. while (it.hasNext()) {
  893. if (b) sb.append(",");
  894. writeParamString(sb, it.next(), set);
  895. b = true;
  896. }
  897. sb.append("]");
  898. } else if (obj.getClass().isArray()) {
  899. sb.append("[");
  900. boolean b = false;
  901. int n = Array.getLength(obj);
  902. for (int i = 0; i < n; i++) {
  903. if (b) sb.append(",");
  904. writeParamString(sb, Array.get(obj, i), set);
  905. b = true;
  906. }
  907. sb.append("]");
  908. } else if (obj instanceof Map) {
  909. sb.append("{");
  910. Map<?, ?> map = (Map<?, ?>) obj;
  911. boolean b = false;
  912. Object key;
  913. Iterator<?> it = map.keySet().iterator();
  914. while (it.hasNext()) {
  915. if (b) sb.append(",");
  916. key = it.next();
  917. jencode(key.toString(), sb);
  918. sb.append(":");
  919. writeParamString(sb, map.get(key), set);
  920. b = true;
  921. }
  922. sb.append("}");
  923. } else {
  924. sb.append("{");
  925. if (!set.contains(obj) && obj.getClass() != Object.class && obj.getClass() != Class.class) {
  926. set.add(obj);
  927. try {
  928. boolean b = false;
  929. BeanInfo bi = Introspector.getBeanInfo(obj.getClass(), Object.class);
  930. PropertyDescriptor[] pds = bi.getPropertyDescriptors();
  931. Object res;
  932. Method method;
  933. for (PropertyDescriptor pd : pds) {
  934. method = pd.getReadMethod();
  935. if (method != null) {
  936. if (b) sb.append(",");
  937. jencode(pd.getName(), sb);
  938. sb.append(":");
  939. res = method.invoke(obj, new Object[0]);
  940. writeParamString(sb, res, set);
  941. b = true;
  942. }
  943. }
  944. } catch (Exception e) {
  945. throw new IOException(e);
  946. }
  947. set.remove(obj);
  948. }
  949. sb.append("}");
  950. }
  951. }
  952.  
  953. private static void jencode(String str, StringBuilder sb) {
  954. sb.append("\"");
  955. char c;
  956. for (int i = 0; i < str.length(); i++) {
  957. c = str.charAt(i);
  958. if (c == '\\') {
  959. sb.append("\\\\");
  960. } else if (c == '/') {
  961. sb.append("\\/");
  962. } else if (c == '\n') {
  963. sb.append("\\n");
  964. } else if (c == '\r') {
  965. sb.append("\\r");
  966. } else if (c == '\t') {
  967. sb.append("\\t");
  968. } else if (c == '\'') {
  969. sb.append("\\\'");
  970. } else if (c == '\"') {
  971. sb.append("\\\"");
  972. } else {
  973. sb.append(c);
  974. }
  975. }
  976. sb.append("\"");
  977. }
  978.  
  979. private static boolean isXDocData(String name, String value) {
  980. if (name.equals("_xdoc") || name.equals("_xdata")) {
  981. if (value.startsWith("./")
  982. || value.startsWith("<")
  983. || value.startsWith("{")
  984. || value.startsWith("[")
  985. || value.startsWith("data:")
  986. || name.equals("_xdoc") && value.startsWith("text:")) {
  987. return false;
  988. } else {
  989. return true;
  990. }
  991. }
  992. return false;
  993. }
  994.  
  995. private static String getFormat(String url) {
  996. String format = "xdoc";
  997. int pos = url.lastIndexOf(".");
  998. if (pos > 0) {
  999. format = url.substring(pos + 1).toLowerCase();
  1000. if (format.equals("zip")) {
  1001. url = url.substring(0, pos);
  1002. pos = url.lastIndexOf(".");
  1003. if (pos > 0) {
  1004. format = url.substring(pos + 1).toLowerCase() + ".zip";
  1005. }
  1006. }
  1007. }
  1008. return format;
  1009. }
  1010.  
  1011. private static String encode(Object str) {
  1012. try {
  1013. return URLEncoder.encode(String.valueOf(str), "UTF-8");
  1014. } catch (UnsupportedEncodingException e) {
  1015. return String.valueOf(str);
  1016. }
  1017. }
  1018.  
  1019. private static String decode(String str) {
  1020. try {
  1021. return URLDecoder.decode(str, "UTF-8");
  1022. } catch (UnsupportedEncodingException e) {
  1023. return str;
  1024. }
  1025. }
  1026.  
  1027. private static void pipe(InputStream in, OutputStream out) throws IOException {
  1028. int len;
  1029. byte[] buf = new byte[4096];
  1030. while (true) {
  1031. len = in.read(buf);
  1032. if (len > 0) {
  1033. out.write(buf, 0, len);
  1034. } else {
  1035. break;
  1036. }
  1037. }
  1038. out.flush();
  1039. out.close();
  1040. in.close();
  1041. }
  1042.  
  1043. private static boolean isFile(String url) {
  1044. int pos = url.indexOf(':');
  1045. return pos < 0
  1046. || pos == 1
  1047. || (pos == 2 && url.charAt(0) == '/');
  1048. }
  1049.  
  1050. private static String toDataURI(InputStream in) throws IOException {
  1051. ByteArrayOutputStream out = new ByteArrayOutputStream();
  1052. pipe(in, out);
  1053. StringBuffer sb = new StringBuffer();
  1054. sb.append("data:application/octet-stream;base64,");
  1055. sb.append(toBase64(out.toByteArray()));
  1056. return sb.toString();
  1057. }
  1058.  
  1059. private static String toDataURI(String url) throws IOException {
  1060. if (url.length() > 0) {
  1061. StringBuffer sb = new StringBuffer();
  1062. String format = null;
  1063. ;
  1064. InputStream in = null;
  1065. if (isFile(url) || url.startsWith("class://")) {
  1066. int pos = url.lastIndexOf('.');
  1067. if (pos > 0) {
  1068. format = url.substring(pos + 1);
  1069. if (format.equals("jpg")) {
  1070. format = "jpeg";
  1071. } else if (format.equals("htm")) {
  1072. format = "html";
  1073. }
  1074. if (format.equals("png") || format.equals("jpeg") || format.equals("gif")) {
  1075. format = "image/" + format;
  1076. } else if (format.equals("html") || format.equals("xml")) {
  1077. format = "text/" + format;
  1078. } else {
  1079. format = "application/" + format;
  1080. }
  1081. }
  1082. if (url.startsWith("class://")) {
  1083. String cls = url.substring(8, url.indexOf("/", 8));
  1084. String path = url.substring(url.indexOf("/", 8) + 1);
  1085. try {
  1086. in = Class.forName(cls).getResourceAsStream(path);
  1087. } catch (Exception e) {
  1088. throw new IOException(e);
  1089. }
  1090. } else {
  1091. in = new FileInputStream(url);
  1092. }
  1093. } else {
  1094. URLConnection conn = new URL(url).openConnection();
  1095. in = conn.getInputStream();
  1096. format = ((HttpURLConnection) conn).getContentType();
  1097. }
  1098. if (format == null) {
  1099. format = "application/octet-stream";
  1100. }
  1101. ByteArrayOutputStream out = new ByteArrayOutputStream();
  1102. pipe(in, out);
  1103. sb.append("data:").append(format).append(";base64,");
  1104. sb.append(toBase64(out.toByteArray()));
  1105. return sb.toString();
  1106. } else {
  1107. return "";
  1108. }
  1109. }
  1110.  
  1111. private static String toBase64(final byte[] data) {
  1112. final char[] out = new char[((data.length + 2) / 3) * 4];
  1113. for (int i = 0, index = 0; i < data.length; i += 3, index += 4) {
  1114. boolean quad = false;
  1115. boolean trip = false;
  1116.  
  1117. int val = (0xFF & data[i]);
  1118. val <<= 8;
  1119. if ((i + 1) < data.length) {
  1120. val |= (0xFF & data[i + 1]);
  1121. trip = true;
  1122. }
  1123. val <<= 8;
  1124. if ((i + 2) < data.length) {
  1125. val |= (0xFF & data[i + 2]);
  1126. quad = true;
  1127. }
  1128. out[index + 3] = alphabet[(quad ? (val & 0x3F) : 64)];
  1129. val >>= 6;
  1130. out[index + 2] = alphabet[(trip ? (val & 0x3F) : 64)];
  1131. val >>= 6;
  1132. out[index + 1] = alphabet[val & 0x3F];
  1133. val >>= 6;
  1134. out[index + 0] = alphabet[val & 0x3F];
  1135. }
  1136. return new String(out);
  1137. }
  1138.  
  1139. private static char[] alphabet =
  1140. "ABCDEFGHIJKLMNOPQRSTUVWXYZabcdefghijklmnopqrstuvwxyz0123456789+/=".toCharArray();
  1141. private static byte[] codes = new byte[256];
  1142.  
  1143. static {
  1144. for (int i = 0; i < 256; i++) {
  1145. codes[i] = -1;
  1146. }
  1147. for (int i = 'A'; i <= 'Z'; i++) {
  1148. codes[i] = (byte) (i - 'A');
  1149. }
  1150. for (int i = 'a'; i <= 'z'; i++) {
  1151. codes[i] = (byte) (26 + i - 'a');
  1152. }
  1153. for (int i = '0'; i <= '9'; i++) {
  1154. codes[i] = (byte) (52 + i - '0');
  1155. }
  1156. codes['+'] = 62;
  1157. codes['/'] = 63;
  1158. }
  1159.  
  1160. private static String[] csvSplit(String str) {
  1161. List<List<String>> list = csvList(str);
  1162. if (list.size() > 0) {
  1163. List<String> cols = (List<String>) list.get(0);
  1164. String[] strs = new String[cols.size()];
  1165. for (int i = 0; i < strs.length; i++) {
  1166. strs[i] = cols.get(i);
  1167. }
  1168. return strs;
  1169. } else {
  1170. return new String[0];
  1171. }
  1172. }
  1173.  
  1174. private static List<List<String>> csvList(String txt) {
  1175. if (txt.length() > 0) {
  1176. ArrayList<List<String>> rows = new ArrayList<List<String>>();
  1177. ArrayList<String> cols = new ArrayList<String>();
  1178. rows.add(cols);
  1179. char c;
  1180. boolean strBegin = false;
  1181. StringBuffer sb = new StringBuffer();
  1182. for (int i = 0; i < txt.length(); i++) {
  1183. c = txt.charAt(i);
  1184. if (strBegin) {
  1185. if (c == '"') {
  1186. if (i + 1 < txt.length()) {
  1187. if (txt.charAt(i + 1) == '"') {
  1188. sb.append(c);
  1189. i++;
  1190. } else {
  1191. strBegin = false;
  1192. }
  1193. } else {
  1194. strBegin = false;
  1195. }
  1196. } else {
  1197. sb.append(c);
  1198. }
  1199. } else {
  1200. if (c == ',') {
  1201. cols.add(sb.toString());
  1202. sb.setLength(0);
  1203. } else if (c == '\n') {
  1204. cols.add(sb.toString());
  1205. sb.setLength(0);
  1206. cols = new ArrayList<String>();
  1207. rows.add(cols);
  1208. } else if (c == '"') {
  1209. strBegin = true;
  1210. } else if (c != '\r') {
  1211. sb.append(c);
  1212. }
  1213. }
  1214. }
  1215. if (sb.length() > 0) {
  1216. cols.add(sb.toString());
  1217. }
  1218. return rows;
  1219. } else {
  1220. return new ArrayList<List<String>>();
  1221. }
  1222. }
  1223.  
  1224. /**
  1225. * XDOC注解
  1226. *
  1227. * @author XDOC
  1228. */
  1229. @Target(ElementType.TYPE)
  1230. @Retention(RetentionPolicy.RUNTIME)
  1231. @Documented
  1232. public @interface XDoc {
  1233. /**
  1234. * xdoc
  1235. *
  1236. * @return
  1237. */
  1238. public String value() default "";
  1239. }
  1240.  
  1241. /**
  1242. * XDOC参数注解
  1243. *
  1244. * @author XDOC
  1245. */
  1246. @Target(ElementType.FIELD)
  1247. @Retention(RetentionPolicy.RUNTIME)
  1248. @Documented
  1249. public @interface XParam {
  1250. /**
  1251. * 参数名称
  1252. *
  1253. * @return
  1254. */
  1255. public String value() default "";
  1256. }
  1257.  
  1258. }

XDocService工具类

Java报表统计导出Word-xdocin方式的更多相关文章

  1. Java使用velocity导出word

    效果展示: 使用word编辑好模板

  2. 关于java中用itext导出word的一点想法

    这几天在项目组只做了很少的事情,主要还是自己不认真地说.我的部分是要负责用itext导出word文档这一块,之前看到大佬们做出了EXCEL部分觉得很是惊奇,就像刚刚接触HTML一样的感觉.但是毕竟自己 ...

  3. Java用freemarker导出word

    概述 最近一个项目要导出word文档,折腾老半天,发现还是用freemarker的模板来搞比较方便省事,现总结一下关键步骤,供大家参考,这里是一个简单的试卷生成例子. 详细 代码下载:http://w ...

  4. Java使用freemarker导出word文档

    通过freemarker,以及JAVA,导出word文档. 共分为三步: 第一步:创建模板文件 第二步:通过JAVA创建返回值. 第三步:执行 分别介绍如下: 第一步: 首先创建word文档,按照想要 ...

  5. 【转】Java通过IText导出word和pdf

    原帖地址:http://blog.csdn.net/zwx19921215/article/details/34439851 最近做的项目中需要用到把Highcharts图表导出word和pdf的功能 ...

  6. Java 将html导出word格式

    @RequestMapping("download") public void exportWord( HttpServletRequest request, HttpServle ...

  7. java用iText导出word文档

    1.需要导入的jar包 2.导出word并下载其实是分两步的. 第一步是将需要导出的数据导出(上传)到服务器上 第二步是将服务器上的文档下载到本地 3. 第一步.上传文档 (1)设置响应信息以及构造上 ...

  8. Java用freemarker导出Word 文档

    1.用Microsoft Office Word打开word原件: 2.把需要动态修改的内容替换成***,如果有图片,尽量选择较小的图片几十K左右,并调整好位置: 3.另存为,选择保存类型Word 2 ...

  9. Java使用freemarker导出word和excel

    www.linxiaosheng.com/post/2013-12-05/40060346181 https://github.com/upyun/java-sdk

随机推荐

  1. HTTPS那些事 用java实现HTTPS工作原理

    HTTPS那些事 用java实现HTTPS工作原理 博客分类: java历险   今天被问到关于https原理的问题,结果由于知识掌握不牢靠,停留于表面,很多细节都无法回答清楚,于是决定把https的 ...

  2. 【敬业福bug】支付宝五福卡敬业福太难求 被炒至200元

    016年央视春晚官方独家互动合作伙伴--支付宝,正式上线春晚红包玩法集福卡活动. 用户新加入10个支付宝好友,就可以获成3张福卡.剩下2张须要支付宝好友之间相互赠送.交换,终于集齐5张福卡就有机会平分 ...

  3. ZOJ 2397:Tian Ji -- The Horse Racing

    Tian Ji -- The Horse Racing Time Limit: 5 Seconds      Memory Limit: 32768 KB Here is a famous story ...

  4. 洛谷 P2055 [ ZJOI 2009 ] 假期的宿舍 —— 二分图匹配

    题目:https://www.luogu.org/problemnew/show/P2055 二分图匹配: 注意要连边的话对方必须有床! 代码如下: #include<iostream> ...

  5. E20170617-hm

    notation   n. 记号,标记法; implicit   adj. 不言明[含蓄]的; 无疑问的,绝对的; 成为一部份的; 内含的; selector   n. 选择者,选择器; promot ...

  6. 记录第一次在egret项目中使用Puremvc

    这几天跟着另一个前端在做一个小游戏,使用的是egret引擎和puremvc框架,这对于我来说还是个比较大的突破吧,特此记录下. 因为在此项目中真是的用到了mvc及面向对象编程,值得学习 记录第一次在e ...

  7. Django返回json给钱前台的方法

    return HttpResponse(simplejson.dumps(resource.update_status, ensure_ascii=False))

  8. Hadoop基础(二)

    HDFS 读写流程 我们知道在HDFS中我们的文件按数据块进行存储,那么当我们写入或者读取一个文件的时候HDFS到底进行了哪些操作呢? HDFS 写流程 如上图所示,假如我们有一个四个节点的集群,并且 ...

  9. MVC系列学习(十三)-合并JS和CSS

    1.先来看看,不用合并js的情况,传输量大 1.1新建一个 [基本]的mvc项目 然后新建一个控制器HomeController,因为js会在很多视图中用到,所以此时我们添加一个视图带布局页Index ...

  10. struts2.1.6存在中文乱码的bug

    如题,后续版本中已解决:可以通过添加filter的方式解决.