最新消息:Welcome to the puzzle paradise for programmers! Here, a well-designed puzzle awaits you. From code logic puzzles to algorithmic challenges, each level is closely centered on the programmer's expertise and skills. Whether you're a novice programmer or an experienced tech guru, you'll find your own challenges on this site. In the process of solving puzzles, you can not only exercise your thinking skills, but also deepen your understanding and application of programming knowledge. Come to start this puzzle journey full of wisdom and challenges, with many programmers to compete with each other and show your programming wisdom! Translated with DeepL.com (free version)

javascript - React js read the text of a docdocx file - Stack Overflow

matteradmin3PV0评论

I need to read the contents of a doc/docx file, which is uploaded by the user.

I've tried using jszip with docxtemplater, but I'm unable to read the file.

If besides the docs/docx files it could also read the txt files, that would be great.

I have a docx file like this:

Io sottoscritto/a __NOME__
nato a __CITTA_NASCITA__(__SIGLA_CITTA_NASCITA__) il __DATA_NASCITA__
residente a __RESIDENZA__   in via __VIA_RESIDENZA__    n __NUMERO_RESIDENZA__.

Can you give me a hand?

Link: =/src/App.js:0-2711

Code:

import React, { useState } from "react";
import { TextField } from "@material-ui/core";
import Docxtemplater from "docxtemplater";
import JSZip from "jszip";

export default function App() {
  const [state, setState] = useState({
    original: [],
    edit: [],
    arrayO: [],
    arrayE: []
  });
  const { original, edit, arrayO, arrayE } = state;

  const showFile = async (e) => {
    e.preventDefault();
    const reader = new FileReader();
    reader.onload = async ({ target: { result } }) => {
      /*const reg = /__[A-Z]+(?:_[A-Z]+)*__/gi;
      const row = result.split("\n");
      let arrayO = result.match(reg);
      setState((prev) => ({
        ...prev,
        original: row,
        edit: row,
        arrayO,
        arrayE: arrayO
      }));*/

      var zip = new JSZip();
      zip.loadAsync(result).then(function (zip) {
        var doc = new Docxtemplater().loadZip(zip);
        var text = doc.getFullText();
        console.log(text);
      });
    };
    reader.readAsText(e.target.files[0]);
  };

  const onChange = (value, label, key) => {
    console.log(value, label, key);
    console.log(
      original.map((e, k) =>
        e.includes(label)
          ? value === ""
            ? label
            : e.replace(label, value)
          : edit[k]
      )
    );
    setState((prev) => ({
      ...prev,
      edit: prev.original.map((e, k) =>
        e.includes(label)
          ? value === ""
            ? label
            : e.replace(label, value)
          : prev.edit[k]
      ),
      arrayE: prev.arrayE.map((e, k) =>
        k === key ? (value === "" ? label : value) : e
      )
    }));
  };

  console.log(state);

  return (
    <div className="App">
      <div style={{ flex: 1 }}>
        <div style={{}}>
          <input type="file" onChange={(e) => showFile(e)} />
          {arrayO.map((label, key) => (
            <div key={key} style={{ paddingTop: 5 }}>
              <TextField
                id="outlined-basic"
                label={label}
                variant="outlined"
                size={"small"}
                onChange={({ target: { value } }) =>
                  onChange(value, label, key)
                }
              />
            </div>
          ))}
        </div>
        <div>
          {edit.map((el, key) => (
            <div key={key}>{el}</div>
          ))}
        </div>
      </div>
      <div style={{ flex: 1, backgroundColor: "#4287f5" }}>
        {arrayO.map((el, key) => (
          <div key={key}>{el}</div>
        ))}
      </div>
      <div style={{ flex: 1, backgroundColor: "#f5cb42" }}>
        {arrayE.map((el, key) => (
          <div key={key}>{el}</div>
        ))}
      </div>
    </div>
  );
}

I need to read the contents of a doc/docx file, which is uploaded by the user.

I've tried using jszip with docxtemplater, but I'm unable to read the file.

If besides the docs/docx files it could also read the txt files, that would be great.

I have a docx file like this:

Io sottoscritto/a __NOME__
nato a __CITTA_NASCITA__(__SIGLA_CITTA_NASCITA__) il __DATA_NASCITA__
residente a __RESIDENZA__   in via __VIA_RESIDENZA__    n __NUMERO_RESIDENZA__.

Can you give me a hand?

Link: https://codesandbox.io/s/lively-butterfly-ey8og?file=/src/App.js:0-2711

Code:

import React, { useState } from "react";
import { TextField } from "@material-ui/core";
import Docxtemplater from "docxtemplater";
import JSZip from "jszip";

export default function App() {
  const [state, setState] = useState({
    original: [],
    edit: [],
    arrayO: [],
    arrayE: []
  });
  const { original, edit, arrayO, arrayE } = state;

  const showFile = async (e) => {
    e.preventDefault();
    const reader = new FileReader();
    reader.onload = async ({ target: { result } }) => {
      /*const reg = /__[A-Z]+(?:_[A-Z]+)*__/gi;
      const row = result.split("\n");
      let arrayO = result.match(reg);
      setState((prev) => ({
        ...prev,
        original: row,
        edit: row,
        arrayO,
        arrayE: arrayO
      }));*/

      var zip = new JSZip();
      zip.loadAsync(result).then(function (zip) {
        var doc = new Docxtemplater().loadZip(zip);
        var text = doc.getFullText();
        console.log(text);
      });
    };
    reader.readAsText(e.target.files[0]);
  };

  const onChange = (value, label, key) => {
    console.log(value, label, key);
    console.log(
      original.map((e, k) =>
        e.includes(label)
          ? value === ""
            ? label
            : e.replace(label, value)
          : edit[k]
      )
    );
    setState((prev) => ({
      ...prev,
      edit: prev.original.map((e, k) =>
        e.includes(label)
          ? value === ""
            ? label
            : e.replace(label, value)
          : prev.edit[k]
      ),
      arrayE: prev.arrayE.map((e, k) =>
        k === key ? (value === "" ? label : value) : e
      )
    }));
  };

  console.log(state);

  return (
    <div className="App">
      <div style={{ flex: 1 }}>
        <div style={{}}>
          <input type="file" onChange={(e) => showFile(e)} />
          {arrayO.map((label, key) => (
            <div key={key} style={{ paddingTop: 5 }}>
              <TextField
                id="outlined-basic"
                label={label}
                variant="outlined"
                size={"small"}
                onChange={({ target: { value } }) =>
                  onChange(value, label, key)
                }
              />
            </div>
          ))}
        </div>
        <div>
          {edit.map((el, key) => (
            <div key={key}>{el}</div>
          ))}
        </div>
      </div>
      <div style={{ flex: 1, backgroundColor: "#4287f5" }}>
        {arrayO.map((el, key) => (
          <div key={key}>{el}</div>
        ))}
      </div>
      <div style={{ flex: 1, backgroundColor: "#f5cb42" }}>
        {arrayE.map((el, key) => (
          <div key={key}>{el}</div>
        ))}
      </div>
    </div>
  );
}
Share Improve this question asked Jun 16, 2021 at 11:53 PaulPaul 4,51215 gold badges69 silver badges156 bronze badges
Add a ment  | 

1 Answer 1

Reset to default 2

I've changed the showfile function to use the result from the file reader to feed it into the PizZip instance :

const showFile = async (e) => {
  console.log('showfile', e)
  e.preventDefault();
  const reader = new FileReader();
  reader.onload = async (e) => {
    const content = e.target.result;
    var doc = new Docxtemplater(new PizZip(content), {delimiters: {start: '12op1j2po1j2poj1po', end: 'op21j4po21jp4oj1op24j'}});
    var text = doc.getFullText();
    console.log(text)
  };
  reader.readAsBinaryString(e.target.files[0]);
};

Note that I put some random string for the start and end delimiters to avoid parsing the document as a template.

Post a comment

comment list (0)

  1. No comments so far