首页 > 解决方案 > 如何使用 Node js 编写具有 ANSI 编码的 CSV 文件

问题描述

我在使用 mongoDB 中的数据创建 CSV 文件时遇到问题。我正在使用快速 csv。数据写在乌克兰语上,这就是为什么我看到的不是“Чоловік”,而是“пїЅпїЅпїЅпїЅпїЅпїЅ”。(数名患者已经存在于数据库中)

const express = require("express");
const bodyParser = require("body-parser");
const mongoose = require("mongoose");
const updateRouter = require('./update-router');
const fs = require('fs');
const fastcsv = require('fast-csv');
var iconv = require('iconv-lite');
const app = express();
//-----------------------------------------------------
app.use(bodyParser.urlencoded({
  extended: true
}));

app.use(express.static("public"));
app.use('/updatepage', updateRouter);
app.use((req, res, next) => {
  console.log(req.method + " : " + req.url);
  next();
});
app.set("view engine", "ejs");

//-----------------------------------------------------

mongoose.connect('mongodb+srv://admin-vlad:VP25102001VP@hospitalproject.cxdut.mongodb.net/hospital', {
  useNewUrlParser: true
});

const patientsSchema = {
  historyOfPatient: {
    type: Number,
    unique: true,
    required: true
  },
  surnameOfPatient: String,
  nameOfPatient: String,
  midnameOfPatient: String,
  genderOfPatient: String,
  dateOfBirthday: String,
  dateOfBirthdayForUpdate: String,
  ageOfPatient: Number,
  ageGroupOfPatient: String,
  addressofPatient: String,
  dateOfArriving: String,
  dateOfArrivingForSearching: Date,
  dateOfArrivingForUpdate: String,
  dateOfBeingFree: String,
  dateOfBeingFreeForUpdate: String,
  bedDayOfPatient: String,
  extraHospitalOfPatient: String,
  sickTimeOfPatient: String,
  pibOfDocOfPatient: String,
  rezultOfreatmentOfPatient: String,
  ripDateOfPatient: String,
  mainDiagnosisOfPatient: String,
  mkxDiagnosisOfPatient: String,
  complicationOfPatient: String,
  сoncomitantDiagnosisOfPatient: String,
  surgeryOfPatient: String,
  laparoscopicSurgeryOfPatient: String,
  nameOfSurgeryOfPatient: String,
  dateOfSurgeryOfPatient: String,
  dateOfSurgeryOfPatientForUpdate: String,
  surgeryDoctorOfPatient: String,
  firstAssistantOfPatient: String,
  secondAssistantOfPatient: String,
  beforeSurgeryOfPatient: Number,
  afterSurgeryOfPatient: Number,
  typeOfSurgeryOfPatient: String,
  sumSurgeryOfPatient: String,
  nameOfSumSurgeryOfPatient: String,
  typeOfSumSurgeryOfPatient: String,
  complicationAfterSurgeryOfPatient: String,
  typeOfComplicationOfPatient: String,
  anotherTypeOfComplicationOfPatient: String

};

const Patient = mongoose.model("Patient", patientsSchema);

app.post("/findAll", function(req, res) {
  Patient.find({}, function(err, foundP) {
    if (!err) {
      if (foundP != null) {

        const ws = fs.createWriteStream("public/files/ListOfPatients.csv");
        let headers = Object.keys(Patient.schema.paths)
          .filter(k => ['_id', '__v', 'dateOfBirthdayForUpdate', 'dateOfArrivingForSearching',
            'dateOfArrivingForUpdate', 'dateOfBeingFreeForUpdate', 'dateOfSurgeryOfPatientForUpdate'
          ].indexOf(k) === -1);

        console.log(headers);

        fastcsv.write(foundP, {headers}).on("finish", function() {
          console.log("Write to ListOfPatients.csv successfully!");
        }).pipe(ws);

        res.render("find", {
          foundPat: foundP
        });
        console.log(foundP);
      }
    }
  });

});

//------------------------------------------------------
let port = process.env.PORT;
if (port == null || port == "") {
  port = 3000;
}
app.listen(port, function() {
  console.log("Server has started successfully");
});

此外,我试图将 iconv 仅用于一个字段以查看它是否有效:

fastcsv.write(foundP.map(item => {
          console.log(item.genderOfPatient);
         return {
          ...item,
          genderOfPatient: iconv.encode(item.genderOfPatient,'win1251')
        }}), {
          headers
        }).on("finish", function() {
          console.log("Write to ListOfPatients.csv successfully!");
        }).pipe(ws);

甚至下载按钮中的属性 charset="windows-1252" 也无济于事:

<a href="files/ListOfPatients.csv" charset="windows-1252" class="form-btn" download="ListOfPatients.csv"><button type="button" class="btn btn-danger btn-sm">Excel</button></a>

标签: javascriptnode.jsmongodbexpressmongoose

解决方案


推荐阅读