当前位置:   article > 正文

Apache Openoffice(2):Java实现word、excel、ppt、txt等办公文件在线预览功能_java实现在线预览excel并保存

java实现在线预览excel并保存

项目文件结构如下:

 

1、项目的pom文件中引入依赖

  1. <?xml version="1.0" encoding="UTF-8"?>
  2. <project xmlns="http://maven.apache.org/POM/4.0.0" xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance"
  3. xsi:schemaLocation="http://maven.apache.org/POM/4.0.0 https://maven.apache.org/xsd/maven-4.0.0.xsd">
  4. <modelVersion>4.0.0</modelVersion>
  5. <parent>
  6. <groupId>org.springframework.boot</groupId>
  7. <artifactId>spring-boot-starter-parent</artifactId>
  8. <version>2.7.5</version>
  9. <relativePath/> <!-- lookup parent from repository -->
  10. </parent>
  11. <groupId>com.example</groupId>
  12. <artifactId>demo</artifactId>
  13. <version>0.0.1-SNAPSHOT</version>
  14. <name>demo</name>
  15. <description>Demo project for Spring Boot</description>
  16. <properties>
  17. <java.version>1.8</java.version>
  18. </properties>
  19. <dependencies>
  20. <dependency>
  21. <groupId>org.springframework.boot</groupId>
  22. <artifactId>spring-boot-starter-web</artifactId>
  23. </dependency>
  24. <dependency>
  25. <groupId>org.springframework.boot</groupId>
  26. <artifactId>spring-boot-starter-test</artifactId>
  27. <scope>test</scope>
  28. </dependency>
  29. <!-- office to pdf need install something start -->
  30. <dependency>
  31. <groupId>com.artofsolving</groupId>
  32. <artifactId>jodconverter</artifactId>
  33. <version>2.2.1</version>
  34. </dependency>
  35. <dependency>
  36. <groupId>org.openoffice</groupId>
  37. <artifactId>ridl</artifactId>
  38. <version>4.1.2</version>
  39. </dependency>
  40. <dependency>
  41. <groupId>org.openoffice</groupId>
  42. <artifactId>juh</artifactId>
  43. <version>4.1.2</version>
  44. </dependency>
  45. <dependency>
  46. <groupId>org.openoffice</groupId>
  47. <artifactId>jurt</artifactId>
  48. <version>4.1.2</version>
  49. </dependency>
  50. <dependency>
  51. <groupId>org.openoffice</groupId>
  52. <artifactId>unoil</artifactId>
  53. <version>4.1.2</version>
  54. </dependency>
  55. <!-- office to pdf need install something end-->
  56. <!-- commons-io start -->
  57. <dependency>
  58. <groupId>commons-io</groupId>
  59. <artifactId>commons-io</artifactId>
  60. <version>2.8.0</version>
  61. </dependency>
  62. <!-- commons-io end -->
  63. <!-- jackson start -->
  64. <dependency>
  65. <groupId>com.fasterxml.jackson.core</groupId>
  66. <artifactId>jackson-databind</artifactId>
  67. <version>2.12.1</version>
  68. </dependency>
  69. <dependency>
  70. <groupId>com.fasterxml.jackson.core</groupId>
  71. <artifactId>jackson-core</artifactId>
  72. <version>2.12.1</version>
  73. </dependency>
  74. <dependency>
  75. <groupId>com.fasterxml.jackson.core</groupId>
  76. <artifactId>jackson-annotations</artifactId>
  77. <version>2.12.1</version>
  78. </dependency>
  79. <!-- jackson end -->
  80. <!-- log start -->
  81. <dependency>
  82. <groupId>org.slf4j</groupId>
  83. <artifactId>slf4j-api</artifactId>
  84. <version>1.7.25</version>
  85. </dependency>
  86. <dependency>
  87. <groupId>ch.qos.logback</groupId>
  88. <artifactId>logback-core</artifactId>
  89. <version>1.2.3</version>
  90. </dependency>
  91. <dependency>
  92. <groupId>ch.qos.logback</groupId>
  93. <artifactId>logback-classic</artifactId>
  94. <version>1.2.3</version>
  95. </dependency>
  96. <!-- log end -->
  97. <dependency>
  98. <groupId>org.apache.commons</groupId>
  99. <artifactId>commons-lang3</artifactId>
  100. <version>3.10</version>
  101. </dependency>
  102. </dependencies>
  103. <build>
  104. <plugins>
  105. <plugin>
  106. <groupId>org.springframework.boot</groupId>
  107. <artifactId>spring-boot-maven-plugin</artifactId>
  108. </plugin>
  109. </plugins>
  110. </build>
  111. </project>

2、SmartStringUtil字符串操作工具类

  1. package com.example.demo.util;
  2. import org.apache.commons.lang3.StringUtils;
  3. import java.util.ArrayList;
  4. import java.util.HashSet;
  5. import java.util.List;
  6. import java.util.Set;
  7. public class SmartStringUtil extends StringUtils {
  8. // ===============split =======================
  9. public static Set<String> splitConvertToSet(String str, String split) {
  10. if (isEmpty(str)) {
  11. return new HashSet<String>();
  12. }
  13. String[] splitArr = str.split(split);
  14. HashSet<String> set = new HashSet<String>(splitArr.length);
  15. for (String string : splitArr) {
  16. set.add(string);
  17. }
  18. return set;
  19. }
  20. public static List<String> splitConvertToList(String str, String split) {
  21. if (isEmpty(str)) {
  22. return new ArrayList<String>();
  23. }
  24. String[] splitArr = str.split(split);
  25. ArrayList<String> list = new ArrayList<String>(splitArr.length);
  26. for (String string : splitArr) {
  27. list.add(string);
  28. }
  29. return list;
  30. }
  31. // ===============split Integer=======================
  32. public static List<Integer> splitConverToIntList(String str, String split, int defaultVal) {
  33. if (isEmpty(str)) {
  34. return new ArrayList<Integer>();
  35. }
  36. String[] strArr = str.split(split);
  37. List<Integer> list = new ArrayList<Integer>(strArr.length);
  38. for (int i = 0; i < strArr.length; i++) {
  39. try {
  40. int parseInt = Integer.parseInt(strArr[i]);
  41. list.add(parseInt);
  42. } catch (NumberFormatException e) {
  43. list.add(defaultVal);
  44. continue;
  45. }
  46. }
  47. return list;
  48. }
  49. public static Set<Integer> splitConverToIntSet(String str, String split, int defaultVal) {
  50. if (isEmpty(str)) {
  51. return new HashSet<Integer>();
  52. }
  53. String[] strArr = str.split(split);
  54. HashSet<Integer> set = new HashSet<Integer>(strArr.length);
  55. for (int i = 0; i < strArr.length; i++) {
  56. try {
  57. int parseInt = Integer.parseInt(strArr[i]);
  58. set.add(parseInt);
  59. } catch (NumberFormatException e) {
  60. set.add(defaultVal);
  61. continue;
  62. }
  63. }
  64. return set;
  65. }
  66. public static Set<Integer> splitConverToIntSet(String str, String split) {
  67. return splitConverToIntSet(str, split, 0);
  68. }
  69. public static List<Integer> splitConverToIntList(String str, String split) {
  70. return splitConverToIntList(str, split, 0);
  71. }
  72. public static int[] splitConvertToIntArray(String str, String split, int defaultVal) {
  73. if (isEmpty(str)) {
  74. return new int[0];
  75. }
  76. String[] strArr = str.split(split);
  77. int[] result = new int[strArr.length];
  78. for (int i = 0; i < strArr.length; i++) {
  79. try {
  80. result[i] = Integer.parseInt(strArr[i]);
  81. } catch (NumberFormatException e) {
  82. result[i] = defaultVal;
  83. continue;
  84. }
  85. }
  86. return result;
  87. }
  88. public static int[] splitConvertToIntArray(String str, String split) {
  89. return splitConvertToIntArray(str, split, 0);
  90. }
  91. // ===============split 2 Long=======================
  92. public static List<Long> splitConverToLongList(String str, String split, long defaultVal) {
  93. if (isEmpty(str)) {
  94. return new ArrayList<Long>();
  95. }
  96. String[] strArr = str.split(split);
  97. List<Long> list = new ArrayList<Long>(strArr.length);
  98. for (int i = 0; i < strArr.length; i++) {
  99. try {
  100. long parseLong = Long.parseLong(strArr[i]);
  101. list.add(parseLong);
  102. } catch (NumberFormatException e) {
  103. list.add(defaultVal);
  104. continue;
  105. }
  106. }
  107. return list;
  108. }
  109. public static List<Long> splitConverToLongList(String str, String split) {
  110. return splitConverToLongList(str, split, 0L);
  111. }
  112. public static long[] splitConvertToLongArray(String str, String split, long defaultVal) {
  113. if (isEmpty(str)) {
  114. return new long[0];
  115. }
  116. String[] strArr = str.split(split);
  117. long[] result = new long[strArr.length];
  118. for (int i = 0; i < strArr.length; i++) {
  119. try {
  120. result[i] = Long.parseLong(strArr[i]);
  121. } catch (NumberFormatException e) {
  122. result[i] = defaultVal;
  123. continue;
  124. }
  125. }
  126. return result;
  127. }
  128. public static long[] splitConvertToLongArray(String str, String split) {
  129. return splitConvertToLongArray(str, split, 0L);
  130. }
  131. // ===============split convert byte=======================
  132. public static List<Byte> splitConverToByteList(String str, String split, byte defaultVal) {
  133. if (isEmpty(str)) {
  134. return new ArrayList<Byte>();
  135. }
  136. String[] strArr = str.split(split);
  137. List<Byte> list = new ArrayList<Byte>(strArr.length);
  138. for (int i = 0; i < strArr.length; i++) {
  139. try {
  140. byte parseByte = Byte.parseByte(strArr[i]);
  141. list.add(parseByte);
  142. } catch (NumberFormatException e) {
  143. list.add(defaultVal);
  144. continue;
  145. }
  146. }
  147. return list;
  148. }
  149. public static List<Byte> splitConverToByteList(String str, String split) {
  150. return splitConverToByteList(str, split, (byte) 0);
  151. }
  152. public static byte[] splitConvertToByteArray(String str, String split, byte defaultVal) {
  153. if (isEmpty(str)) {
  154. return new byte[0];
  155. }
  156. String[] strArr = str.split(split);
  157. byte[] result = new byte[strArr.length];
  158. for (int i = 0; i < strArr.length; i++) {
  159. try {
  160. result[i] = Byte.parseByte(strArr[i]);
  161. } catch (NumberFormatException e) {
  162. result[i] = defaultVal;
  163. continue;
  164. }
  165. }
  166. return result;
  167. }
  168. public static byte[] splitConvertToByteArray(String str, String split) {
  169. return splitConvertToByteArray(str, split, (byte) 0);
  170. }
  171. // ===============split convert double=======================
  172. public static List<Double> splitConverToDoubleList(String str, String split, double defaultVal) {
  173. if (isEmpty(str)) {
  174. return new ArrayList<Double>();
  175. }
  176. String[] strArr = str.split(split);
  177. List<Double> list = new ArrayList<Double>(strArr.length);
  178. for (int i = 0; i < strArr.length; i++) {
  179. try {
  180. double parseByte = Double.parseDouble(strArr[i]);
  181. list.add(parseByte);
  182. } catch (NumberFormatException e) {
  183. list.add(defaultVal);
  184. continue;
  185. }
  186. }
  187. return list;
  188. }
  189. public static List<Double> splitConverToDoubleList(String str, String split) {
  190. return splitConverToDoubleList(str, split, 0);
  191. }
  192. public static double[] splitConvertToDoubleArray(String str, String split, double defaultVal) {
  193. if (isEmpty(str)) {
  194. return new double[0];
  195. }
  196. String[] strArr = str.split(split);
  197. double[] result = new double[strArr.length];
  198. for (int i = 0; i < strArr.length; i++) {
  199. try {
  200. result[i] = Double.parseDouble(strArr[i]);
  201. } catch (NumberFormatException e) {
  202. result[i] = defaultVal;
  203. continue;
  204. }
  205. }
  206. return result;
  207. }
  208. public static double[] splitConvertToDoubleArray(String str, String split) {
  209. return splitConvertToDoubleArray(str, split, 0);
  210. }
  211. // ===============solit convert float=======================
  212. public static List<Float> splitConverToFloatList(String str, String split, float defaultVal) {
  213. if (isEmpty(str)) {
  214. return new ArrayList<Float>();
  215. }
  216. String[] strArr = str.split(split);
  217. List<Float> list = new ArrayList<Float>(strArr.length);
  218. for (int i = 0; i < strArr.length; i++) {
  219. try {
  220. float parseByte = Float.parseFloat(strArr[i]);
  221. list.add(parseByte);
  222. } catch (NumberFormatException e) {
  223. list.add(defaultVal);
  224. continue;
  225. }
  226. }
  227. return list;
  228. }
  229. public static List<Float> splitConverToFloatList(String str, String split) {
  230. return splitConverToFloatList(str, split, 0f);
  231. }
  232. public static float[] splitConvertToFloatArray(String str, String split, float defaultVal) {
  233. if (isEmpty(str)) {
  234. return new float[0];
  235. }
  236. String[] strArr = str.split(split);
  237. float[] result = new float[strArr.length];
  238. for (int i = 0; i < strArr.length; i++) {
  239. try {
  240. result[i] = Float.parseFloat(strArr[i]);
  241. } catch (NumberFormatException e) {
  242. result[i] = defaultVal;
  243. continue;
  244. }
  245. }
  246. return result;
  247. }
  248. public static float[] splitConvertToFloatArray(String str, String split) {
  249. return splitConvertToFloatArray(str, split, 0f);
  250. }
  251. // ===============upperCase=======================
  252. /**
  253. * 将首字母大写
  254. *
  255. * @param str
  256. * @return
  257. */
  258. public static String upperCaseFirstChar(String str) {
  259. if (str == null || str.isEmpty()) {
  260. return str;
  261. }
  262. char firstChar = str.charAt(0);
  263. if (Character.isUpperCase(firstChar)) {
  264. return str;
  265. }
  266. char[] values = str.toCharArray();
  267. values[0] = Character.toUpperCase(firstChar);
  268. return new String(values);
  269. }
  270. }

3、将word、excel、ppt转换为pdf流的工具类代码

  1. package com.example.demo.util;
  2. import com.artofsolving.jodconverter.DefaultDocumentFormatRegistry;
  3. import com.artofsolving.jodconverter.DocumentConverter;
  4. import com.artofsolving.jodconverter.DocumentFormat;
  5. import com.artofsolving.jodconverter.openoffice.connection.OpenOfficeConnection;
  6. import com.artofsolving.jodconverter.openoffice.connection.SocketOpenOfficeConnection;
  7. import com.artofsolving.jodconverter.openoffice.converter.StreamOpenOfficeDocumentConverter;
  8. import java.io.*;
  9. import java.net.HttpURLConnection;
  10. import java.net.URL;
  11. import java.net.URLConnection;
  12. public class FileConvertUtil {
  13. /** 默认转换后文件后缀 */
  14. private static final String DEFAULT_SUFFIX = "pdf";
  15. /** openoffice_port */
  16. private static final Integer OPENOFFICE_PORT = 8100;
  17. private static final String CONNECT_IP = "192.168.222.131";
  18. /**
  19. * 方法描述 office文档转换为PDF(处理本地文件)
  20. *
  21. * @param sourcePath 源文件路径
  22. * @param suffix 源文件后缀
  23. * @return InputStream 转换后文件输入流
  24. * @author tarzan
  25. */
  26. public static InputStream convertLocaleFile(String sourcePath, String suffix) throws Exception {
  27. File inputFile = new File(sourcePath);
  28. InputStream inputStream = new FileInputStream(inputFile);
  29. return covertCommonByStream(inputStream, suffix);
  30. }
  31. /**
  32. * 方法描述 office文档转换为PDF(处理网络文件)
  33. *
  34. * @param netFileUrl 网络文件路径
  35. * @param suffix 文件后缀
  36. * @return InputStream 转换后文件输入流
  37. * @author tarzan
  38. */
  39. public static InputStream convertNetFile(String netFileUrl, String suffix) throws Exception {
  40. // 创建URL
  41. URL url = new URL(netFileUrl);
  42. // 试图连接并取得返回状态码
  43. URLConnection urlconn = url.openConnection();
  44. urlconn.connect();
  45. HttpURLConnection httpconn = (HttpURLConnection) urlconn;
  46. int httpResult = httpconn.getResponseCode();
  47. if (httpResult == HttpURLConnection.HTTP_OK) {
  48. InputStream inputStream = urlconn.getInputStream();
  49. return covertCommonByStream(inputStream, suffix);
  50. }
  51. return null;
  52. }
  53. /**
  54. * 方法描述 将文件以流的形式转换
  55. *
  56. * @param inputStream 源文件输入流
  57. * @param suffix 源文件后缀
  58. * @return InputStream 转换后文件输入流
  59. * @author tarzan
  60. */
  61. public static InputStream covertCommonByStream(InputStream inputStream, String suffix) throws Exception {
  62. ByteArrayOutputStream out = new ByteArrayOutputStream();
  63. OpenOfficeConnection connection = new SocketOpenOfficeConnection(CONNECT_IP,OPENOFFICE_PORT);
  64. connection.connect();
  65. DocumentConverter converter = new StreamOpenOfficeDocumentConverter(connection);
  66. DefaultDocumentFormatRegistry formatReg = new DefaultDocumentFormatRegistry();
  67. DocumentFormat targetFormat = formatReg.getFormatByFileExtension(DEFAULT_SUFFIX);
  68. DocumentFormat sourceFormat = formatReg.getFormatByFileExtension(suffix);
  69. converter.convert(inputStream, sourceFormat, out, targetFormat);
  70. connection.disconnect();
  71. return outputStreamConvertInputStream(out);
  72. }
  73. /**
  74. * 方法描述 outputStream转inputStream
  75. *
  76. * @author tarzan
  77. */
  78. public static ByteArrayInputStream outputStreamConvertInputStream(final OutputStream out) throws Exception {
  79. ByteArrayOutputStream baos=(ByteArrayOutputStream) out;
  80. return new ByteArrayInputStream(baos.toByteArray());
  81. }
  82. public static void main(String[] args) throws IOException {
  83. //convertNetFile("http://172.16.10.21/files/home/upload/department/base/201912090541573c6abdf2394d4ae3b7049dcee456d4f7.doc", ".pdf");
  84. //convert("c:/Users/admin/Desktop/2.pdf", "c:/Users/admin/Desktop/3.pdf");
  85. }
  86. }

4、iservice层在线预览方法代码

  1. package com.example.demo.service;
  2. import javax.servlet.http.HttpServletResponse;
  3. public interface onlineService {
  4. void onlinePreview(String url, HttpServletResponse response) throws Exception;
  5. }

5、service层在线预览方法代码

  1. package com.example.demo.service.impl;
  2. import com.example.demo.service.onlineService;
  3. import com.example.demo.util.FileConvertUtil;
  4. import com.example.demo.util.SmartStringUtil;
  5. import org.springframework.stereotype.Service;
  6. import javax.servlet.http.HttpServletResponse;
  7. import java.io.InputStream;
  8. import java.io.OutputStream;
  9. @Service
  10. public class onlineServiceImpl implements onlineService {
  11. /**
  12. * @Description:系统文件在线预览接口
  13. * @Author: tarzan
  14. */
  15. @Override
  16. public void onlinePreview(String url, HttpServletResponse response) throws Exception {
  17. //获取文件类型
  18. String[] str = SmartStringUtil.split(url,"\\.");
  19. if(str.length==0){
  20. throw new Exception("文件格式不正确");
  21. }
  22. String suffix = str[str.length-1];
  23. if(!suffix.equals("txt") && !suffix.equals("doc") && !suffix.equals("docx") && !suffix.equals("xls")
  24. && !suffix.equals("xlsx") && !suffix.equals("ppt") && !suffix.equals("pptx")){
  25. throw new Exception("文件格式不支持预览");
  26. }
  27. InputStream in= FileConvertUtil.convertNetFile(url,suffix);
  28. OutputStream outputStream = response.getOutputStream();
  29. //创建存放文件内容的数组
  30. byte[] buff =new byte[1024];
  31. //所读取的内容使用n来接收
  32. int n;
  33. //当没有读取完时,继续读取,循环
  34. while((n=in.read(buff))!=-1){
  35. //将字节数组的数据全部写入到输出流中
  36. outputStream.write(buff,0,n);
  37. }
  38. //强制将缓存区的数据进行输出
  39. outputStream.flush();
  40. //关流
  41. outputStream.close();
  42. in.close();
  43. }
  44. }

6、controler层代码

  1. package com.example.demo.controller;
  2. import com.example.demo.service.onlineService;
  3. //import io.swagger.annotations.ApiOperation;
  4. import org.springframework.beans.factory.annotation.Autowired;
  5. import org.springframework.web.bind.annotation.*;
  6. import javax.servlet.http.HttpServletResponse;
  7. @RestController
  8. public class onlineController {
  9. @Autowired
  10. onlineService onlineService1;
  11. // @ApiOperation(value = "系统文件在线预览接口 by tarzan")
  12. @PostMapping("/api/file/onlinePreview")
  13. public void onlinePreview(@RequestParam("url") String url, HttpServletResponse response) throws Exception{
  14. onlineService1.onlinePreview(url,response);
  15. }
  16. }

7、postman测试

传入文件的URL

 弹出文件下载框,如果实在浏览器则会弹出页面

 

声明:本文内容由网友自发贡献,转载请注明出处:【wpsshop】
推荐阅读
相关标签
  

闽ICP备14008679号