The client

Add download event for Export button

/* ** src/components/employee/index.tsx */
class Employee extends Component<Props.State> {... handleDownload =() = > {
    // DOWNLOAD_EMPLOYEE_URL: "/api/employee/downloadEmployee"
    window.open(DOWNLOAD_EMPLOYEE_URL); }; .render(){... <Button type="primary"
      icon={<DownloadOutlined />}
      onClick={this.handleDownload}
      className="right"> export < / Button >; . }}Copy the code

The service side

excel-export

We select Excel -export to process the Download of Excel on the Node side.

Because there is no declaration file for the excel-export, we need to add an excel-export.d.ts first.

/* * routes/excel-export.d.ts */
declare module "excel-export" {
  export function execute(config: Config) :void;
  export interface Config {
    cols: { caption: string; type: string} []; rows:any[]; }}Copy the code

The specific implementation

/* ** routes/employee.ts */
import excelExport from "excel-export";

let conf: excelExport.Config = {
  cols: [{caption: "Employee ID".type: "number" },
    { caption: "Name".type: "string" },
    { caption: "Department".type: "string" },
    { caption: "Entry Time".type: "string" },
    { caption: "Rank".type: "string"},].rows: [],}; router.get("/downloadEmployee".async (req, res) => {
  try {
    let result = await query(queryAllSQL); // Connect to the database to query all employee information
    conf.rows = result.map((i: any) = > [
      i.id,
      i.name,
      i.department,
      i.hiredate,
      i.level,
    ]);
    let excel = excelExport.execute(conf);

    // Set the return header
    res.setHeader(
      "Content-Type"."application/vnd.openxmlformats-officedocument.spreadsheetml.sheet"
    );
    res.setHeader("Content-Disposition"."attachment; filename=employee.xlsx");

    // Finally write a binary file
    res.end(excel, "binary");
  } catch(error) { res.send(e.toString()); }});Copy the code

Content-Type

Content-type: Used to indicate the MIME Type (media Type) of the resource, telling the client the Content Type of the actual returned Content.

extension The document type The MIME type
.xlsx Microsoft Excel (OpenXML) application/vnd.openxmlformats-officedocument.spreadsheetml.sheet

Content-Disposition

Content-disposition: Indicates whether the Content of the reply should be displayed inline (i.e. a web page or part of a page) or downloaded and saved locally as an attachment.

Attachment: indicates that the message body should be downloaded locally; Most browsers present a “save as” dialog box that, paired with filename, serves as the default filename to present to the user in the “save as” dialog box.

The results of

TS + Nodejs series

  • TS + Nodejs: Quickly build a server development environment
  • TS + Nodejs: connects/manipulates the database
  • TS + Nodejs: Handles Excel file downloads