国产探花免费观看_亚洲丰满少妇自慰呻吟_97日韩有码在线_资源在线日韩欧美_一区二区精品毛片,辰东完美世界有声小说,欢乐颂第一季,yy玄幻小说排行榜完本

首頁 > 編程 > JavaScript > 正文

NodeJs之word文件生成與解析的實現(xiàn)代碼

2019-11-19 11:54:43
字體:
供稿:網(wǎng)友

一,介紹與需求

 1.1,介紹

1, officegen 模塊可以為Microsoft Office 2007及更高版本生成Office Open XML文件。此模塊不依賴于任何框架,您不需要安裝Microsoft Office,因此您可以將它用于任何類型的 JavaScript 應(yīng)用程序。輸出也是流而不是文件,不依賴于任何輸出工具。此模塊應(yīng)適用于支持Node.js 0.10或更高版本的任何環(huán)境,包括Linux,OSX和Windows。

2, textract 文本提取節(jié)點模塊。

3, pdf2json 是一個節(jié)點。js模塊解析和轉(zhuǎn)換PDF從二進制到j(luò)son格式,它是用PDF構(gòu)建的。并通過瀏覽器外的交互式表單元素和文本內(nèi)容解析對其進行擴展。其目標是在web服務(wù)中包裝時啟用帶有交互式表單元素的服務(wù)器端PDF解析,并在作為命令行實用程序使用時啟用將本地PDF解析為json文件。

1.2,需求

二,文件生成導(dǎo)出

第一步:安裝 officegen

cnpm install officegen --save

第二步:引入officegen

var officegen = require('officegen');var fs = require('fs');var docx = officegen('docx');//wordvar pptx = officegen('pptx');//pptx

第三步:使用officegen docx

... docx.on('finalize', function (written) {    console.log('Finish to create Word file./nTotal bytes created: ' + written + '/n');  });  docx.on('error', function (err) {    console.log(err);  });... //var tows = ['id', 'provinceZh', 'leaderZh', 'cityZh', 'cityEn'];//創(chuàng)建一個和表頭對應(yīng)且名稱與數(shù)據(jù)庫字段對應(yīng)數(shù)據(jù),便于循環(huán)取出數(shù)據(jù)      var pObj = docx.createP({ align: 'center' });// 創(chuàng)建行 設(shè)置居中 大標題      pObj.addText('全國所有城市', { bold: true, font_face: 'Arial', font_size: 18 });// 添加文字 設(shè)置字體樣式 加粗 大小      // let towsLen = tows.length      let dataLen = data.length      for (var i = 0; i < dataLen; i++) {//循環(huán)數(shù)據(jù)庫得到的數(shù)據(jù),因為取出的數(shù)據(jù)格式為        //[{"id" : "101010100","provinceZh" : "北京","leaderZh" : "北京","cityZh" : "北京","cityEn" : "beijing"},{…………},{…………}]        /************************* 文本 *******************************/        // var pObj = docx.createP();//創(chuàng)建一行        // pObj.addText(`(${i+1}), `,{ bold: true, font_face: 'Arial',});        // pObj.addText(`省級:`,{ bold: true, font_face: 'Arial',});        // pObj.addText(`${data[i]['provinceZh']} `,);        // pObj.addText(`市級:`,{ bold: true, font_face: 'Arial',});        // pObj.addText(`${data[i]['leaderZh']} `);        // pObj.addText(`縣區(qū):`,{ bold: true, font_face: 'Arial',});        // pObj.addText(`${data[i]['cityZh']}`);        /************************* 表格 *******************************/        let SingleRow = [data[i]['id'], data[i]['provinceZh'], data[i]['leaderZh'], data[i]['cityZh']]        table.push(SingleRow)      }      docx.createTable(table, tableStyle);      var out = fs.createWriteStream('out.docx');// 文件寫入      out.on('error', function (err) {        console.log(err);      });      var result = docx.generate(out);// 服務(wù)端生成word      res.writeHead(200, {        // 注意這里的type設(shè)置,導(dǎo)出不同文件type值不同application/vnd.openxmlformats-officedocument.wordprocessingml.document        "Content-Type": "application/vnd.openxmlformats-officedocument.wordprocessingml.document",        'Content-disposition': 'attachment; filename=out' + moment(new Date().getTime()).format('YYYYMMDDhhmmss') + '.docx'      });      docx.generate(res);// 客戶端導(dǎo)出word

第四步:拋出接口

router.put('/download/word', function (req, res) {  console.log('exportWord-------------');  docx.on('finalize', function (written) {    console.log('Finish to create Word file./nTotal bytes created: ' + written + '/n');  });  docx.on('error', function (err) {    console.log(err);  });  let fields = {    id: '',    provinceZh: '',    leaderZh: '',    cityZh: '',    cityEn: ''  }  var table = [    [{      val: "No.",      opts: {        align: "center",        vAlign: "center",        sz: '36',        // cellColWidth: 42,        // b:true,        // sz: '48',        // shd: {        //  fill: "7F7F7F",        //  themeFill: "text1",        //  "themeFillTint": "80"        // },        // fontFamily: "Avenir Book"      }    }, {      val: "省份",      opts: {        align: "center",        vAlign: "center",        sz: '36',        // b:true,        // color: "A00000",        // align: "right",        // shd: {        //  fill: "92CDDC",        //  themeFill: "text1",        //  "themeFillTint": "80"        // }      }    }, {      val: "市",      opts: {        align: "center",        vAlign: "center",        sz: '36',        // cellColWidth: 42,        // b:true,        // sz: '48',        // shd: {        //  fill: "92CDDC",        //  themeFill: "text1",        //  "themeFillTint": "80"        // }      }    }, {      val: "區(qū)/縣",      opts: {        align: "center",        vAlign: "center",        sz: '36',        // cellColWidth: 42,        // b:true,        // sz: '48',        // shd: {        //  fill: "92CDDC",        //  themeFill: "text1",        //  "themeFillTint": "80"        // }      }    }],  ]  var tableStyle = {    tableColWidth: 2400,    tableSize: 24,    tableColor: "ada",    tableAlign: "center",    tableVAlign: "center",    tableFontFamily: "Comic Sans MS",    borders: true  }  MongoDbAction.getFieldsByConditions('AllCity', {}, fields, function (err, data) {//根據(jù)需求查詢想要的字段    if (err) {      //執(zhí)行出錯    } else {      //var tows = ['id', 'provinceZh', 'leaderZh', 'cityZh', 'cityEn'];//創(chuàng)建一個和表頭對應(yīng)且名稱與數(shù)據(jù)庫字段對應(yīng)數(shù)據(jù),便于循環(huán)取出數(shù)據(jù)      var pObj = docx.createP({ align: 'center' });// 創(chuàng)建行 設(shè)置居中 大標題      pObj.addText('全國所有城市', { bold: true, font_face: 'Arial', font_size: 18 });// 添加文字 設(shè)置字體樣式 加粗 大小      // let towsLen = tows.length      let dataLen = data.length      for (var i = 0; i < dataLen; i++) {//循環(huán)數(shù)據(jù)庫得到的數(shù)據(jù),因為取出的數(shù)據(jù)格式為        //[{"id" : "101010100","provinceZh" : "北京","leaderZh" : "北京","cityZh" : "北京","cityEn" : "beijing"},{…………},{…………}]        /************************* 文本 *******************************/        // var pObj = docx.createP();//創(chuàng)建一行        // pObj.addText(`(${i+1}), `,{ bold: true, font_face: 'Arial',});        // pObj.addText(`省級:`,{ bold: true, font_face: 'Arial',});        // pObj.addText(`${data[i]['provinceZh']} `,);        // pObj.addText(`市級:`,{ bold: true, font_face: 'Arial',});        // pObj.addText(`${data[i]['leaderZh']} `);        // pObj.addText(`縣區(qū):`,{ bold: true, font_face: 'Arial',});        // pObj.addText(`${data[i]['cityZh']}`);        /************************* 表格 *******************************/        let SingleRow = [data[i]['id'], data[i]['provinceZh'], data[i]['leaderZh'], data[i]['cityZh']]        table.push(SingleRow)      }      docx.createTable(table, tableStyle);      var out = fs.createWriteStream('out.docx');// 文件寫入      out.on('error', function (err) {        console.log(err);      });      var result = docx.generate(out);// 服務(wù)端生成word      res.writeHead(200, {        // 注意這里的type設(shè)置,導(dǎo)出不同文件type值不同application/vnd.openxmlformats-officedocument.wordprocessingml.document        "Content-Type": "application/vnd.openxmlformats-officedocument.wordprocessingml.document",        'Content-disposition': 'attachment; filename=out' + moment(new Date().getTime()).format('YYYYMMDDhhmmss') + '.docx'      });      docx.generate(res);// 客戶端導(dǎo)出word    }  });});

第五步:前端調(diào)用

下載調(diào)用方法

downloadWordOper() {    // var url = "http://localhost:8880/api/v1/yingqi/download/word";    // window.location = url;//這里不能使用get方法跳轉(zhuǎn),否則下載不成功      this.$http(downloadWord()).then((res)=>{       //這里res.data是返回的blob對象       var blob = new Blob([res.data], {type: 'application/vnd.openxmlformats-officedocument.wordprocessingml.document;charset=utf-8'}); //application/vnd.openxmlformats-officedocument.wordprocessingml.document這里表示doc類型       downloadFile(blob,'word','docx')      })     },

downloadFile方法代碼如下:

/**  *下載文件  * @param blob :返回數(shù)據(jù)的blob對象  * @param tagFileName :下載后文件名標記  * @param fileType :文件類 word(docx) excel(xlsx) ppt等  */ export function downloadFile(blob,tagFileName,fileType) {  var downloadElement = document.createElement('a');  var href = window.URL.createObjectURL(blob); //創(chuàng)建下載的鏈接  downloadElement.href = href;  downloadElement.download = tagFileName+moment(new Date().getTime()).format('YYYYMMDDhhmmss')+'.'+fileType; //下載后文件名  document.body.appendChild(downloadElement);  downloadElement.click(); //點擊下載  document.body.removeChild(downloadElement); //下載完成移除元素  window.URL.revokeObjectURL(href); //釋放掉blob對象 }

第六步:下載后的效果

ppt生成下載類似,只是設(shè)置的writeHead類型與使用的方法不一樣

router.put('/download/createPpt', function (req, res) {  console.log('exportPpt-------------');  pptx.on('finalize', function (written) {    console.log('Finish to create ppt file./nTotal bytes created: ' + written + '/n');  });  pptx.on('error', function (err) {    console.log(err);  });  let slide1 = pptx.makeNewSlide();//創(chuàng)建一個新幻燈片  slide1.title = 'PPT文件';  slide1.addText('Office generator', {    y: 66, x: 'c', cx: '50%', cy: 60, font_size: 48,    color: '0000ff'  });  slide1.addText('Big Red', {    y: 250, x: 10, cx: '70%',    font_face: 'Wide Latin', font_size: 54,    color: 'cc0000', bold: true, underline: true  });  var out = fs.createWriteStream('out.pptx');// 文件寫入  out.on('error', function (err) {    console.log('error2===',err);  });  var result = pptx.generate(out);// 服務(wù)端生成ppt  res.writeHead(200, {    // 注意這里的type設(shè)置,導(dǎo)出不同文件type值不同application/vnd.openxmlformats-officedocument.presentationml.presentation    // "Content-Type": "application/vnd.openxmlformats-officedocument.presentationml.presentation",    // 'Content-disposition': 'attachment; filename=out' + moment(new Date().getTime()).format('YYYYMMDDhhmmss') + '.pptx'    "Content-Type": "application/vnd.openxmlformats-officedocument.presentationml.presentation",    'Content-disposition': 'attachment; filename=surprise.pptx'  });  pptx.generate(res);// 客戶端導(dǎo)出ppt});

三,文件上傳解析

3.1,word文檔解析

第一步:安裝textract

cnpm install textract --save

第二步:引入textract

//引入textract解析word模塊var textract = require('textract');//對于docx文件,您可以使用textract,它將從.docx文件中提取文本。var fs = require('fs');

第三步:解析文檔

function parseWord(excelConfig, res) {  textract.fromFileWithPath(excelConfig.excel_Dir, function (error, text) {    if (error) {      res.status(200).json({        httpCode: 200,        message: '導(dǎo)入解析失敗',        data: error,        returnValue: 0      });    } else {      res.status(200).json({        httpCode: 200,        message: '導(dǎo)入成功',        data: {          result: text        },        returnValue: 1      });    }  })}

第四步:解析后刪除文檔

fs.unlink(excelConfig.excel_Dir, function (err) {      if (err) throw err;      console.log("刪除文件" + excelConfig.excel_Dir + "成功")    })

第五步:拋出接口調(diào)用后的效果

3.2,pdf文檔解析

第一步:安裝pdf2json

cnpm install pdf2json --save

第二步:引入pdf2json

var PDFParser = require("pdf2json");var fs = require('fs');

第三步:解析文檔

function parsePdf(excelConfig, res) {  var pdfParser = new PDFParser(this, 1);  pdfParser.loadPDF(excelConfig.excel_Dir);  pdfParser.on("pdfParser_dataError", errData => {    res.status(200).json({      httpCode: 200,      message: '導(dǎo)入解析失敗',      data: errData,      returnValue: 0    });  });  pdfParser.on("pdfParser_dataReady", pdfData => {    let data = pdfParser.getRawTextContent()    fs.writeFile('./uploads/test.txt', data, function (err) {      if (err) {        throw err;      }    });    res.status(200).json({      httpCode: 200,      message: '導(dǎo)入成功',      data: {        result: data      },      returnValue: 1    });  });}

第四步:解析后刪除文檔

 fs.unlink(excelConfig.excel_Dir, function (err) {if (err) throw err;console.log("刪除文件" + excelConfig.excel_Dir + "成功")})

第五步:拋出接口調(diào)用后的效果

以上就是本文的全部內(nèi)容,希望對大家的學(xué)習(xí)有所幫助,也希望大家多多支持武林網(wǎng)。

發(fā)表評論 共有條評論
用戶名: 密碼:
驗證碼: 匿名發(fā)表
主站蜘蛛池模板: 乌苏市| 古蔺县| 辽阳市| 麻江县| 奇台县| 平安县| 和龙市| 车致| 井研县| 五寨县| 湖口县| 渭南市| 左贡县| 井陉县| 安陆市| 贺州市| 诸暨市| 泰来县| 博乐市| 常山县| 阳谷县| 平顺县| 北流市| 博乐市| 图木舒克市| 额济纳旗| 潢川县| 胶州市| 米易县| 精河县| 祥云县| 五指山市| 遵义县| 上林县| 兴化市| 纳雍县| 鲜城| 满城县| 会同县| 随州市| 寻甸|