欧美bbbwbbbw肥妇,免费乱码人妻系列日韩,一级黄片

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

 更新時(shí)間:2019年04月01日 11:42:29   作者:jackson影琪  
這篇文章主要介紹了NodeJs之word文件生成與解析的實(shí)現(xiàn)代碼,文中通過(guò)示例代碼介紹的非常詳細(xì),對(duì)大家的學(xué)習(xí)或者工作具有一定的參考學(xué)習(xí)價(jià)值,需要的朋友們下面隨著小編來(lái)一起學(xué)習(xí)學(xué)習(xí)吧

一,介紹與需求

 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é)點(diǎn)模塊。

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

1.2,需求

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

第一步:安裝 officegen

cnpm install officegen --save

第二步:引入officegen

var officegen = require('officegen');
var fs = require('fs');
var docx = officegen('docx');//word
var 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)建一個(gè)和表頭對(duì)應(yīng)且名稱與數(shù)據(jù)庫(kù)字段對(duì)應(yīng)數(shù)據(jù),便于循環(huán)取出數(shù)據(jù)
      var pObj = docx.createP({ align: 'center' });// 創(chuàng)建行 設(shè)置居中 大標(biāo)題
      pObj.addText('全國(guó)所有城市', { 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ù)庫(kù)得到的數(shù)據(jù),因?yàn)槿〕龅臄?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(`省級(jí):`,{ bold: true, font_face: 'Arial',});
        // pObj.addText(`${data[i]['provinceZh']} `,);
        // pObj.addText(`市級(jí):`,{ 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í)行出錯(cuò)
    } else {
      //var tows = ['id', 'provinceZh', 'leaderZh', 'cityZh', 'cityEn'];//創(chuàng)建一個(gè)和表頭對(duì)應(yīng)且名稱與數(shù)據(jù)庫(kù)字段對(duì)應(yīng)數(shù)據(jù),便于循環(huán)取出數(shù)據(jù)
      var pObj = docx.createP({ align: 'center' });// 創(chuàng)建行 設(shè)置居中 大標(biāo)題
      pObj.addText('全國(guó)所有城市', { 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ù)庫(kù)得到的數(shù)據(jù),因?yàn)槿〕龅臄?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(`省級(jí):`,{ bold: true, font_face: 'Arial',});
        // pObj.addText(`${data[i]['provinceZh']} `,);
        // pObj.addText(`市級(jí):`,{ 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對(duì)象
       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 :返回?cái)?shù)據(jù)的blob對(duì)象
  * @param tagFileName :下載后文件名標(biāo)記
  * @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(); //點(diǎn)擊下載
  document.body.removeChild(downloadElement); //下載完成移除元素
  window.URL.revokeObjectURL(href); //釋放掉blob對(duì)象
 }

第六步:下載后的效果

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)建一個(gè)新幻燈片
  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');//對(duì)于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)用后的效果

以上就是本文的全部?jī)?nèi)容,希望對(duì)大家的學(xué)習(xí)有所幫助,也希望大家多多支持腳本之家。

相關(guān)文章

  • Node.js事件的正確使用方法

    Node.js事件的正確使用方法

    這篇文章主要給大家介紹了關(guān)于Node.js事件的正確使用方法,文中通過(guò)示例代碼介紹的非常詳細(xì),對(duì)大家學(xué)習(xí)或者使用Node.js具有一定的參考學(xué)習(xí)價(jià)值,需要的朋友們下面來(lái)一起學(xué)習(xí)學(xué)習(xí)吧
    2019-04-04
  • Node.js  事件循環(huán)詳解及實(shí)例

    Node.js 事件循環(huán)詳解及實(shí)例

    這篇文章主要介紹了 Node.js 事件循環(huán)詳解及實(shí)例的相關(guān)資料,Node.js 有多個(gè)內(nèi)置的事件,我們可以通過(guò)引入 events 模塊,并通過(guò)實(shí)例化 EventEmitter 類來(lái)綁定和監(jiān)聽事件,需要的朋友可以參考下
    2017-08-08
  • node.js中的require使用詳解

    node.js中的require使用詳解

    本文通過(guò)幾個(gè)具體實(shí)例來(lái)分析講解了node.js中require的使用方法,非常的詳盡,這里推薦給大家
    2014-12-12
  • Nodejs全局安裝和本地安裝的不同之處

    Nodejs全局安裝和本地安裝的不同之處

    這篇文章主要介紹了Nodejs全局安裝和本地安裝的不同之處的相關(guān)資料,非常不錯(cuò),具有參考借鑒價(jià)值,需要的朋友可以參考下
    2016-07-07
  • 分析node事件循環(huán)和消息隊(duì)列

    分析node事件循環(huán)和消息隊(duì)列

    node的好處毋庸置疑,事件驅(qū)動(dòng),異步非阻塞I/O,以及處理高并發(fā)的能力深入人心,因此大家喜歡用node做一些小型后臺(tái)服務(wù)或者作為中間層和其他服務(wù)配合完成一些大型應(yīng)用場(chǎng)景。
    2021-06-06
  • 基于Node的Axure文件在線預(yù)覽的實(shí)現(xiàn)代碼

    基于Node的Axure文件在線預(yù)覽的實(shí)現(xiàn)代碼

    這篇文章主要介紹了基于Node的Axure文件在線預(yù)覽的實(shí)現(xiàn)代碼,文中通過(guò)示例代碼介紹的非常詳細(xì),對(duì)大家的學(xué)習(xí)或者工作具有一定的參考學(xué)習(xí)價(jià)值,需要的朋友們下面隨著小編來(lái)一起學(xué)習(xí)學(xué)習(xí)吧
    2019-08-08
  • NodeJs中的VM模塊詳解

    NodeJs中的VM模塊詳解

    這篇文章主要介紹了NodeJs中的VM模塊詳解,本文講解了什么是VM? 、VM模塊的runInThisContext、runInThisContext方法等內(nèi)容,需要的朋友可以參考下
    2015-05-05
  • 使用pm2運(yùn)行node應(yīng)用的流程步驟

    使用pm2運(yùn)行node應(yīng)用的流程步驟

    PM2是一個(gè)功能強(qiáng)大的進(jìn)程管理工具,專為?Node.js?應(yīng)用設(shè)計(jì),它提供了進(jìn)程管理、日志管理、負(fù)載均衡和性能監(jiān)控等功能,幫助開發(fā)者輕松應(yīng)對(duì)生產(chǎn)環(huán)境中的各種挑戰(zhàn),本文給大家介紹了使用pm2?運(yùn)行node應(yīng)用的流程步驟,需要的朋友可以參考下
    2024-03-03
  • node.js中axios使用心得總結(jié)

    node.js中axios使用心得總結(jié)

    這篇文章主要介紹了node.js中axios使用心得總結(jié),以及分析了中間遇到的錯(cuò)誤,大家參考一下。
    2017-11-11
  • koa大型web項(xiàng)目中使用路由裝飾器的方法示例

    koa大型web項(xiàng)目中使用路由裝飾器的方法示例

    這篇文章主要介紹了koa大型web項(xiàng)目中使用路由裝飾器的方法示例,文中通過(guò)示例代碼介紹的非常詳細(xì),對(duì)大家的學(xué)習(xí)或者工作具有一定的參考學(xué)習(xí)價(jià)值,需要的朋友們下面隨著小編來(lái)一起學(xué)習(xí)學(xué)習(xí)吧
    2019-04-04

最新評(píng)論