js
import React, { Component } from 'react';
import XLSX from 'xlsx';
class ExcelWithImages extends Component {
constructor(props) {
super(props);
this.state = {
data: null
}
}
componentDidMount() {
const xhr = new XMLHttpRequest();
xhr.open('GET', 'http://example.com/excel_with_images.xlsx');
xhr.responseType = 'arraybuffer';
xhr.onload = () => {
const data = new Uint8Array(xhr.response);
const workbook = XLSX.read(data, { type: 'array' });
const sheetName = workbook.SheetNames[0];
const worksheet = workbook.Sheets[sheetName];
//将所有单元格转换为html格式
const json = XLSX.utils.sheet_to_html(worksheet);
// 转换html中的图片
const img_pattern = /<img src="(.+?)"/g;
const matches = json.match(img_pattern);
if (matches) {
let html_output = this.parse_html_data(json, matches, workbook, sheetName);
this.setState({ data: html_output });
} else {
this.setState({ data: json });
}
};
xhr.send();
}
parse_html_data = (data, matches, workbook, sheetName) => {
let html_output = data;
for(let i=0; i<matches.length; i++) {
const src = matches[i].substring('<img src="'.length, matches[i].length-1);
const img_data = workbook.Sheets[sheetName][`${src}_full`] ? workbook.Sheets[sheetName][`${src}_full`].w : '';
html_output = html_output.replace(matches[i], `<img src="data:image/png;base64,${img_data}"`);
}
return html_output;
}
render() {
const { data } = this.state;
if (!data) {
return <div>Loading ...</div>;
}
return (
<div dangerouslySetInnerHTML={{ __html: data }} />
);
}
}
export default ExcelWithImages;