Printing Csv, Pdf of Table Data in React and Ant Design.

Printing Csv, Pdf of Table Data in React and Ant Design.

The main importance for printing csv and pdf of table data in react js and ant design is to utilize Ant Design's built-in table features for sorting, filtering, and conditional formatting to enhance the data before exporting. It also helps for seamless integration and customization of export functionality. Comma Separated Values(CSV) and Portable Document Format(PDF) are file formats that are used to easily share or distribute the data with others in a standardized format without requiring them to access the online application.

Firstly, we have to create a React Application as it is the very first important step to take. If you have an existing React Project, you can skip this step.

  • Have Node.js (version 14 or above) and npm (or yarn) installed on your system. You can download them from: https://nodejs.org/

  • Open your Code editor terminal, command prompt or any terminal available on your PC.

  • Navigate to the desired directory for your project.

  • Run the following command:

      npx create-react-app my-app
      (Replace my-app with your desired project name)
    

    This will create a new directory called my-app with the basic React project structure and dependencies installed. You can then start the development server by running:

      cd my-app
      npm start
    

    This will open your default browser and launch the React app at http://localhost:3000/.

Next we Install Dependencies:

  • react-csv: For CSV exports (npm install react-csv or yarn add react-csv)

  • react-to-print: For PDF exports (npm install react-to-print or yarn add react-to-print)

    After installing the dependencies, Prepare Your Ant Design Table:

    • Ensure your table component has a unique ref assigned to it. ref means a reference to a function component, allowing you to call methods directly on the instance. This reference will be used by react-to-print to access the table content.

    • Consider using columns prop to control which columns are exported, especially if you have hidden or dynamic columns.

    • Optionally, create a custom component for the table header to customize its appearance in the exported files.

      Implementing CSV Export

        import { useTable, useCSVExport } from 'react-table';
      
        // ... (Rest of your table component code)
      
        const {
          getTableProps,
          headerGroups,
          rows,
          prepareRow,
        } = useTable(data, columns);
      
        const { downloadCSV } = useCSVExport({
          columns, // Optionally customize exported columns
          filename: 'table_data.csv',
        });
      
        return (
          <div {...getTableProps()}>
            <thead>
              {headerGroups.map((headerGroup) => (
                <tr key={headerGroup.id}>
                  {headerGroup.headers.map((header) => (
                    <th key={header.id}>{header.render('Header')}</th>
                  ))}
                </tr>
              ))}
            </thead>
            <tbody>
              {rows.map((row) => {
                prepareRow(row);
                return (
                  <tr key={row.id}>
                    {row.cells.map((cell) => (
                      <td key={cell.id}>{cell.render('Cell')}</td>
                    ))}
                  </tr>
                );
              })}
            </tbody>
            <button onClick={downloadCSV}>Export to CSV</button>
          </div>
        );
      

      Implementing PDF Export:

        import { useReactToPrint } from 'react-to-print';
      
        // ... (Inside your table component)
      
        const componentRef = useRef();
        const handlePrint = useReactToPrint({
          content: () => componentRef.current,
          documentTitle: 'Table Data', // Optional: Set PDF document title
        });
      
        return (
          <div ref={componentRef}>
            {/* Your table content here */}
          </div>
          <>
            <button onClick={handlePrint}>Print to PDF</button>
          </>
        );
      

      We can also customize the exported data by modifying the columns prop in both CSV and PDF exports. Also for large datasets or more complex formatting needs, you can consider server-side export options.

      I hope this comprehensive guide assists you in effectively printing CSV and PDF versions of your table data in React and Ant Design!