因為工作中需要一個把doc或者docx的office文檔內(nèi)容涉枫,需要讀取出來哪轿,并且也沒展示功能。代碼中第一考慮可能就是通過讀取流方式栏豺,結(jié)果寫了以后彬碱,各種亂碼,百科的解決方案也是千奇百怪冰悠,第一點:可能是文檔編碼格式和項目編碼格式不一致堡妒,需要重新再讀取流時候,重新定義流的編碼格式溉卓;第二點:可能是框架層面直接調(diào)用解析方式皮迟,但是框架封裝沒有聲明編碼格式;第三點:就是在轉(zhuǎn)成流在重建字符串時候桑寨,需要聲明編碼格式伏尼。總之尉尾,就是編碼格式不一致導(dǎo)致爆阶。
當(dāng)然問題不止這么簡單,如果是其他格式的話沙咏,可以通過編碼格式解決辨图,但是這是office的文檔格式,出奇的難受肢藐,愣是編碼不通過故河。
所以需要換一個思路進(jìn)行文檔解析,從中獲取需要的內(nèi)容吆豹。
最后的確定法方案鱼的,通過POI方式,進(jìn)行office文檔解析痘煤。
第一步?mavne項目中需要引入的jar包
? ? ? ? <!--docx文件下載問題-->
? ? ? ? <dependency>
? ? ? ? ? ? <groupId>org.apache.poi</groupId>
? ? ? ? ? ? <artifactId>poi-scratchpad</artifactId>
? ? ? ? ? ? <version>3.8</version>
? ? ? ? </dependency>
? ? ? ? <dependency>
? ? ? ? ? ? <groupId>commons-io</groupId>
? ? ? ? ? ? <artifactId>commons-io</artifactId>
? ? ? ? ? ? <version>2.6</version>
? ? ? ? </dependency>
需要注意事項是凑阶,高版本的POI包,有些不兼容情況衷快,對于下面這個commons-io包一定要引入宙橱,要不然會報錯POI中某個類找尋不到問題。
第二步 新建一個doc解析類
import org.apache.poi.POIXMLDocument;
import org.apache.poi.POIXMLTextExtractor;
import org.apache.poi.hwpf.extractor.WordExtractor;
import org.apache.poi.openxml4j.opc.OPCPackage;
import org.apache.poi.xwpf.extractor.XWPFWordExtractor;
import java.io.File;
import java.io.FileInputStream;
import java.io.InputStream;
/**
* @author admin
* @date 2019/12/4 16:23
*/
public class WordDownload {
? ? /**
? ? * @Description: POI 讀取? word
? ? * @create: 2019-07-27 9:48
? ? * @update logs
? ? * @throws Exception
? ? */
? ? public static String readWord(String filePath) throws Exception{
? ? ? ? File file = new File(filePath);
? ? ? ? if(file.length()==0) return ""; // 需要操作原因是可能會空文件問題,如果不做處理养匈,在下面讀取中會報錯
? ? ? ? StringBuffer sb = new StringBuffer();
? ? ? ? String buffer = "";
? ? ? ? try {
? ? ? ? ? ? if (filePath.endsWith(".doc")) {
? ? ? ? ? ? ? ? InputStream is = new FileInputStream(file);
? ? ? ? ? ? ? ? WordExtractor ex = new WordExtractor(is);
? ? ? ? ? ? ? ? buffer = ex.getText();
? ? ? ? ? ? ? ? if(buffer.length() > 0){
? ? ? ? ? ? ? ? ? ? //使用回車換行符分割字符串
? ? ? ? ? ? ? ? ? ? String [] arry = buffer.split("\\r\\n");
? ? ? ? ? ? ? ? ? ? for (String string : arry) {
? ? ? ? ? ? ? ? ? ? ? ? sb.append(string.trim());
? ? ? ? ? ? ? ? ? ? }
? ? ? ? ? ? ? ? }
? ? ? ? ? ? } else if (filePath.endsWith(".docx")) {
? ? ? ? ? ? ? ? OPCPackage opcPackage = POIXMLDocument.openPackage(filePath);
? ? ? ? ? ? ? ? POIXMLTextExtractor extractor = new XWPFWordExtractor(opcPackage);
? ? ? ? ? ? ? ? buffer = extractor.getText();
? ? ? ? ? ? ? ? if(buffer.length() > 0){
? ? ? ? ? ? ? ? ? ? //使用換行符分割字符串
? ? ? ? ? ? ? ? ? ? String [] arry = buffer.split("\\n");
? ? ? ? ? ? ? ? ? ? for (String string : arry) {
? ? ? ? ? ? ? ? ? ? ? ? sb.append(string.trim());
? ? ? ? ? ? ? ? ? ? }
? ? ? ? ? ? ? ? }
? ? ? ? ? ? } else {
? ? ? ? ? ? ? ? return null;
? ? ? ? ? ? }
? ? ? ? ? ? return sb.toString();
? ? ? ? } catch (Exception e) {
? ? ? ? ? ? System.out.print("error---->"+filePath);
? ? ? ? ? ? e.printStackTrace();
? ? ? ? ? ? return null;
? ? ? ? }
? ? }
}
?