Code Monkey home page Code Monkey logo

react-data-export's Introduction

React-Data-Export

⚠️ A complete re-write is coming soon (we won't need xlsx package anymore (It will be backward compatible)⚠️

🆕 I am re-writing complete excel api in JavaScript, please consider contributing or putting your ideas here https://github.com/securedeveloper/javascript-excel (After finishing will update this library)

(:exclamation::exclamation::exclamation:The purpose of having a new library is that open source libraries either does not support styling and rest functionality in excel or they are too heavy to consider)

npm version dependencies Status devDependencies Status Build Status Vulnerabilities Coverage Status

A data export library built with and for React.

Installation

With npm:

npm install react-data-export --save

Code Examples

Excel Props

Prop Type Default Required Description
hideElement bool false false To hide the button & directly download excel file
filename string Download false Excel file name to be downloaded
fileExtension string xlsx false Download file extension [xlsx]
element HTMLElement <button> false Element to download excel file
children Array<ExcelSheet> null true ExcelSheet Represents data

ExcelSheet Props

Prop Type Default Required Description
name string "" true Sheet name in file
data array<object> null false Excel Sheet data
dataSet array<ExcelSheetData> null false Excel Sheet data
children ExcelColumn null false ExcelColumns

Note: In ExcelSheet props dataSet has precedence over data and children props.

For further types and definitions Read More

Cell Style

Cell styles are specified by a style object that roughly parallels the OpenXML structure. The style object has five top-level attributes: fill, font, numFmt, alignment, and border.

Style Attribute Sub Attributes Values
fill patternType "solid" or "none"
fgColor COLOR_SPEC
bgColor COLOR_SPEC
font name "Calibri" // default
sz "11" // font size in points
color COLOR_SPEC
bold true or false
underline true or false
italic true or false
strike true or false
outline true or false
shadow true or false
vertAlign true or false
numFmt "0" // integer index to built in formats, see StyleBuilder.SSF property
"0.00%" // string matching a built-in format, see StyleBuilder.SSF
"0.0%" // string specifying a custom format
"0.00%;\\(0.00%\\);\\-;@" // string specifying a custom format, escaping special characters
"m/dd/yy" // string a date format using Excel's format notation
alignment vertical "bottom" or "center" or "top"
horizontal "bottom" or "center" or "top"
wrapText true or false
readingOrder 2 // for right-to-left
textRotation Number from 0 to 180 or 255 (default is 0)
90 is rotated up 90 degrees
45 is rotated up 45 degrees
135 is rotated down 45 degrees
180 is rotated down 180 degrees
255 is special, aligned vertically
border top { style: BORDER_STYLE, color: COLOR_SPEC }
bottom { style: BORDER_STYLE, color: COLOR_SPEC }
left { style: BORDER_STYLE, color: COLOR_SPEC }
right { style: BORDER_STYLE, color: COLOR_SPEC }
diagonal { style: BORDER_STYLE, color: COLOR_SPEC }
diagonalUp true or false
diagonalDown true or false

COLOR_SPEC: Colors for fill, font, and border are specified as objects, either:

  • { auto: 1} specifying automatic values
  • { rgb: "FFFFAA00" } specifying a hex ARGB value
  • { theme: "1", tint: "-0.25"} specifying an integer index to a theme color and a tint value (default 0)
  • { indexed: 64} default value for fill.bgColor

BORDER_STYLE: Border style is a string value which may take on one of the following values:

  • thin
  • medium
  • thick
  • dotted
  • hair
  • dashed
  • mediumDashed
  • dashDot
  • mediumDashDot
  • dashDotDot
  • mediumDashDotDot
  • slantDashDot

Borders for merged areas are specified for each cell within the merged area. So to apply a box border to a merged area of 3x3 cells, border styles would need to be specified for eight different cells:

  • left borders for the three cells on the left,
  • right borders for the cells on the right
  • top borders for the cells on the top
  • bottom borders for the cells on the left

Dependencies

This library uses file-saver and xlsx and using json-loader will do the magic for you.

///webpack.config.js
vendor: [
        .....
        'xlsx',
        'file-saver'
],
.....
node: {fs: 'empty'},
externals: [
    {'./cptable': 'var cptable'},
    {'./jszip': 'jszip'}
 ]

react-data-export's People

Stargazers

 avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar

Watchers

 avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar

react-data-export's Issues

Column width

Hey, is there any update on when the ability to change column width will be added to this repo?
Thanks

FEATURE: Make header cell stylable.

My reason:

I Would like for it to be possible to actually style the header cells.

Steps to reproduce:

Make style passable into the header cell.
Currently:
image
Possibility:

function getHeaderCell(v, cellRef, ws, style) {
    var cell = {};
 
    var headerCellStyle = {font: {bold: true}};
    cell.v = v;
    cell.t = 's';
    if(style && style !== undefined){
        cell.s = style;
    } else {
        cell.s = headerCellStyle;
   } 
    ws[cellRef] = cell;
}

And usage is, that you pass in col.style without typechecking, if it is not set, it is undefined, thus defaultstyle (perhaps rename headerCellStyle to defaultStyle) will be applied.
As I can't get the whole package to submit the pull request currently, i typed this out on a mobile. I'm sorry if it is not understandable.

Lib Version: Latest

fs missing

Hey there,

Trying to follow the simple example, but I am getting the following error while compiling:

* fs in ./node_modules/xlsx/xlsx.js, ./node_modules/xlsx/ods.js

I tried running npm install --save fs but it has the same result.

Pass multiple data sources into ExcelSheet

Great job on this package.

I need to pass multiple data sources into ExcelSheet Component, as the sheet is to comprise of many tables. And possible use basic styling like, bold.

Could you, please, help.

Thank you.

Export to CSV and XLS

Hi,

Thanks a lot for your work on this great plugin. I am able to export XLSX files without any problem but you don't mention in the docs how to export to CSV or XLS. Also, does this plugin export to PDF?

Thanks a lot for your help,

Cheers

Can excelColumn value support a.b.c ?

hi, there is my dataSource , just Like

const dataSource = [{
  name: 'John', 
  age:  18,
  info: {
    work: 'programmer',
    location: 'China'
  }
}, {
  name: 'Nany', 
  age:  18,
  info: {
    work: 'programmer',
    location: 'USA'
  }
}]

Is possible to export info.location ?
I try to <ExcelColumn label="location" value="info.location"} />, but it doesn't work

Function to call export excel doesn't' works!

import { default as ExcelFile, ExcelSheet, ExcelColumn } from "react-data-export";

exportExcel = () =>{
      console.log('funzione')
      return(
        <ExcelFile hideElement={true} filename={'Lista Movimenti'+new Date()}>
          <ExcelSheet data={this.state.movimenti} name="Movimenti" >
            <ExcelColumn label="Causale" value="causaleShort"/>
            <ExcelColumn label="Azienda" value="azienda"/>
            <ExcelColumn label="Merchant" value="merchant"/>
            <ExcelColumn label="Data" value="data"/>
            <ExcelColumn label="Importo" value="importo"/>
          </ExcelSheet>
        </ExcelFile>
      )}

No works.. why?

React.Fragment like support?

Is there any support like react fragment give us? group a list of children of various api's data but showing them on one spreedsheet.

Style not showing in excel file (Re-Open#70)

Hi, may I check with you what is the version you are using for xlsx and file-saver? I have re-downloaded react-data-export 0.4.2 and run the same example but the style is still not working.

I am using

xlsx 0.13.5
file-saver 1.3.8
react-data-export 0.4.2

Importing errors

Hi,

I can't resolve import errors.

Webpack 4
React
Babel 6

image

Added vendor
image

Added external & node

image

Maybe I need to include react-data-export ir xlsx folder to my module rules?
image

Active Sheet - Feature

Active Sheet - Feature

My reason:

Having the ability to choose an active sheet based upon a prop on ExcelFile.

Cell Alignment failed

I have tried many ways but haven't succeeded in cell alignment changed to right. Please let me know if this is possible. I have used readingOrder.

{ value: "H1", style: { alignment: { readingOrder: 1} } },

{ value: "H1", style: { alignment: { readingOrder: 2} } },

Is there anything I'm doing wrong here.
Thanks.

Recommended process for conditional columns (getting corrupt file)

Awesome library. Thanks for the work on this!

I think a common use case is that the user only want certain columns on their export. I accomplished this via an array of columns with each column being added if it matches some conditional (because you get errors if you try to put a conditional as a child of in the jsx). Example of how I did this:

// column you always want to include
let allColumns = [<ExcelColumn label="Name" value="name" key="name" />]  

// conditional adding of additional columns passed on props
if (this.props.exportOptions.email) {
    allColumns.push(<ExcelColumn label="Email" value="email" key="email" />);
}

// finally, map the columns
<ExcelSheet data={candidates}>
    {allColumns.map(el => el)}
</ExcelSheet>

ISSUE:
When I export the file on a machine that has Excel, I get an error message from Excel that the file is corrupted.

QUESTIONS:
If there is a better way - or this is the preferred way - can the README be updated? (My error may be caused by something else)
If this is likely the reason I am seeing my error, could you let me know why?

No git binary found in $PATH

When I try to install react-data-export, npm complains that no git binary found. Usually npm does not require git executables to be present on the system. However, if I do put git in my path it works. It is a huge impediment during deployment because I can't guarantee that git client is installed on the server.

issue

PoSh Newbie

I am brand new to PoSh and I am looking for some assistance with, I am assuming an easy for you all script. I have to pull data from Excel (ONLY 2 columns of LastName, FirstName, 15 Rows) into PoSh, then into a new Excel spreadsheet, putting the 2 columns of data into 1 column. Any help would be grealy appreciated!

Iphone Problem.

For some reason that i can not understand when I'm trying to export the xlsx from an iphone the is download a .dms file and not the xlsx file. Can anyone help me with that?

Error when installing API

I'm facing an issue when trying to install latest version of react-data-export.
I've added "react-data-export": "^0.3.7" to my POM.xml and I'm receiving the following error:
[ERROR] npm ERR! Error while executing:
[ERROR] npm ERR! C:\Program Files (x86)\Git\bin\git.EXE ls-remote -h -t https://github.com/securedeveloper/js-xlsx.git
[ERROR] npm ERR!
[ERROR] npm ERR! fatal: unable to access 'https://github.com/securedeveloper/js-xlsx.git/': Could not resolve host: github.com
[ERROR] npm ERR!
[ERROR] npm ERR! exited with error code: 128

I had previously installed version 0.3.2 and was working fine.
Is someone having similar issues?

Thanks.

TypeError: s.t.match is not a function

I'm using 'Excel Export with custom cells style' example and adding dynamic content. When I'm using your example then excelsheet is downloading with correct data but when I'm passing dynamic data then it's showing error

TypeError: s.t.match is not a function

If I restart my server then many times this error not showing but data also not fetch in excelsheet after download

Sample code is here

import React, {Component} from 'react';
import ReactExport from 'react-data-export';
import _ from 'underscore'

const ExcelFile = ReactExport.ExcelFile;
const ExcelSheet = ReactExport.ExcelFile.ExcelSheet;

class App extends Component {
	constructor(props) {
		super(props);

		this.state = {
			multiDataSet: []
		}
	}

	componentDidMount() {
		this.callFakeApi()
	}

	callFakeApi() {
		fetch('https://jsonplaceholder.typicode.com/posts')
		.then(response => response.json())
		.then(json => {
			console.log(json)
			this.convertDataFormat(json)
		})
	}

	convertDataFormat(json) {
		const jsonHeader = _.keys(json[0])
		const data = json.map((obj, i) => {
			const array = []
			if (i % 2 === 0) {
				var style = {fill: {patternType: "solid", fgColor: {rgb: "FFFF0000"}}}
			} else {
				var style = {}
			}
			jsonHeader.map((columnName) => {
				array.push({value: obj[columnName], style})
			})
			return array
		})
		const multiDataSet = [{columns: jsonHeader, data: data}]
		console.log(multiDataSet)
		this.setState({
			multiDataSet
		})
	}

	render() {
		return (
			<div>
				<ExcelFile element={<button>Download Data With Styles</button>}>
					<ExcelSheet dataSet={this.state.multiDataSet} name="Organization"/>
				</ExcelFile>
			</div>
		);
	}
}

export default App

Title/header for tables in case of multiple data sets

Hi,

(This is my first time raising an issue on github. So forgive for my newbieness)
(I dont know if this should be an issue or a feature request.)

In case of multiple data sets, is there any way that we could have titles/headers for the individual tables? As an example:

image

Thanks in advance :).

Resolve dependencies in react-parcel project

Hi,

I working on a react project which is built on Parcel bundler instead of Webpack.

React Data Export used file-saver, json-loader and xlsx. I have installed all these dependencies in my package.json. But the application still throwing the below error,

Uncaught Error: Cannot find module 'jszip'
at newRequire (src.61e5e814.js:39)
at localRequire (src.61e5e814.js:54)
at make_xlsx (xlsx.js:1344)
at Object.parcelRequire.../node_modules/react-data-export/node_modules/xlsx/xlsx.js../dist/cpexcel (xlsx.js:6)

I have also installed the 'jszip' module. But same result.

How can I fix this issue?

Thanks,
Adi

React native

Hello, does it works with react native? thanks!

Styling exported table

Hello, any chance of being able to style the exported data? I would like to create a band for the header column to differentiate it. Probably style multiple datasets differently, possibly add caption for data and brand the document with the organization name and logo. Thanks. Love this package.

Fetch data before download

My reason: app needs to get the data before downloading it

Steps to reproduce:

Lib Version:

Is there any way to keep react-data-export from exporting until after the app gets the data. In all of the examples the data is already available but I have a case where I need to fetch the data to be exported only when the user clicks the export button.

Error by importing the project

Hello,

I'm trying to use this exciting library. After installing the react-data-export package in my existing react application I get an error when I import the package by using import ReactExport from 'react-data-export';

I have the following error.

../framework/~/tempa-xlsx/xlsx.js
Module not found: Error: Cannot resolve module 'fs' in /home/ogodon/projects/framework/node_modules/tempa-xlsx
resolve module fs in /home/ogodon/projects/framework/node_modules/tempa-xlsx
  looking for modules in /home/ogodon/projects/company/node_modules
    /home/ogodon/projects/company/node_modules/fs doesn't exist (module as directory)
    resolve 'file' fs in /home/ogodon/projects/company/node_modules
      resolve file

Module fs cannot be found. So my question would be : is this package only meant to be used on a server context ?

Thank you for your time.

Cannot import to use this useful library

After I installed react-data-export, xlsx, json-loader, file-saver packages and coded following your example, I faced with this error :

Warning: React.createElement: type is invalid -- expected a string (for built-in components) or a class/function (for composite components) but got: undefined. You likely forgot to export your component from the file it's defined in, or you might have mixed up default and named imports.

This is my webpack,config.js :
https://paste.ubuntu.com/p/TpF4swZcKB/

Typescript definitions for components

Suggestion:

I would like to use this library in a typescript project. I tried to type the index.js file, but I couldn't find a way to express the export definitions in typescript. So I changed the index.js file, but this would be a breaking change in the API.
In addition I exported the react component with the existing typings and referenced the types in the package.json.

Please let me know if you would accept a pull request, which introduces breaking changes or if you have any idea how to correctly type index.js.

My reason:

I would like to use this library with typescript.

Steps to reproduce:

Check the changes in the fork. https://github.com/daugsbi/react-data-export

Style not showing in excel file

I am able to download an excel file with the example provided, i.e. Excel Export with custom cells style. However, the styles could not be applied to the cells. Am I missing out on something for the example to work?
capture

Columns Key

Is there any way to use the column key and title like this
{title: "Name", dataKey: "name"}, for multidataset.

please provide some examples how properly use it

wrote a function, calling it and nothing happens, no error and no anything else

const excel = () => {
  return (
    <ExcelFile>
       <ExcelSheet data={this.state.entities.results} name="Orders">
           <ExcelColumn label="Name" value="name" />
           <ExcelColumn label="Created at" value="createdAt" />
       </ExcelSheet>
     </ExcelFile>
  );
};

return excel();

hide the download button

Hi,

Thanks for building this awesome package. I want to make a small change where we give a prop to hide the download button. So if we have a prop hideElement set to true on ExcelFile, we directly download the file without rendering the download button. I made the change and have a branch ready. Please let me know how I can push the changes and create a Pull request for this.

Nested objects

Json List for data
[{
id: 1,
name: "Bariatric Bed AH 1",
img_thumb: [ 
"tn-arjo-huntleigh-bariatric-bed-2.jpg" ],
asset_positions: [
{
id: 2,
name: John
}
]},
{
id: 2,
name: "Bariatric Bed AH 1",
img_thumb: [ 
"tn-arjo-huntleigh-bariatric-bed-2.jpg" ],
asset_positions: [
{
id: 2,
Name: Peter
}
]}
}
]

I want to get asset_positions.name .
I tried value= {(col) => col.asset_positions.name}. But still it is not working.

Props not defined

Hello, I got the folowwing error when I tried to integrate the export feature:

Uncaught ReferenceError: props is not defined
    at ExcelFile.render (ExcelFile.js:148)

I got it working in a fresh create-react-app, but not in my main app (the basic example with sample data)

thanks in advance!

File exports without xlsx extension

I'm saving a file with multiple datasets as it is in the docs. The data exports but without the xlsx extension, hence reads as invalid.
If I rename the file with the xlsx extension, it opens well with excel.
I use create-react-app, so I don't have access to the webpack config.
Thanks for your help. Expecting.

First fetch data from server then export xlsx file with same click

First I want to fetch data with API then that data should download with react-data-export.
For this, I want to use single button for both work.

this time, I'm using like this -
<Button onClick={this.fetchData}>Fetch Data</Button>

fetchData() {
  axios.get('api_link')
    .then(({data}) => {
      this.setState({data})
    })
}

and then Download data -

<ExcelFile element={<button>Download Data</button>}>
	<ExcelSheet data={data} name="Employees">
		<ExcelColumn label="Name" value="name"/>
		<ExcelColumn label="Wallet Money" value="amount"/>
		<ExcelColumn label="Gender" value="sex"/>
		<ExcelColumn label="Marital Status" value={(col) => col.is_married ? "Married" : "Single"}/>
	</ExcelSheet>
</ExcelFile>

but Buttons will show 2 times. it's not good looking for users.

So, How can I fetch and download data with only one click ?

ExcelColumn width and style prop - Feature

Pass a width prop to the ExcelColumn component.

My reason:

It would be nice to set the width for the column, so it can fit all the content inside the column's cells.
Maybe even implementing a prop for styling on ExcelColumn as well. I think it would be great being able to style the column titles.

Can't open files downloaded on Mac

Hello! I'm using this library for a few days now without trouble on Ubuntu. The downloaded file opens correctly on my PC and Windows, but for some reason I get this error when trying to open the same file on a Mac:

“Excel could not open … because some content is unreadable”

I transferred the same file to my Ubuntu and it opens normally.

Has anyone gone through this? Maybe some encoding issue? I can't find anything on GitHub. I'm using version 0.4.2 and my code is pretty much the same as the example:

https://github.com/securedeveloper/react-data-export/blob/master/examples/with_custom_download_element.md

Thanks in advance!

Change download button title

Hi,

Thanks a lot for your work on this great plugin. I would like to change the default button "Download" text and there is nothing in the doc mentioning that, I have made tons of research ? Could you please help me 🙏🏻

Thanks a lot for your help,

Cheers

Handling Nested Objects

In the provided examples, the json object is flat. If you want to use a dataset with nested objects, be aware that it may not be so clear how to access the nested object attribute.

Here is the structure of my dataset:

activitiesList
[{ "id": 1, "activityName": "My Fundraiser" "organization": { "id": 10, "organizationName": "My Organization", }, { "id": 2, "activityName": "My Fundraiser 2" "organization": { "id": 10, "organizationName": "My Organization", }]

I tried to pickup the organization's id as organization.id but it didn't work.

<ExcelSheet data={activitiesList} name="Activities">
                    <ExcelColumn label="Organization ID" value="organization.id"/>
                </ExcelSheet>

I found that a way to do it is the following:

<ExcelSheet data={activitiesList} name="Activities">
                    <ExcelColumn label="Organization ID" value={(col) => col.organization.organizationInitials}/>
                </ExcelSheet>

It would be helpful if we could show an example of how to deal with nested objects.

Thanks!

not able to use Colspan

Hello,
I am not able to add the colspan in my code. Can anyone suggest how to add the colspan or else any styles we can add to make it look like colspan.
Great library !!

Recommend Projects

  • React photo React

    A declarative, efficient, and flexible JavaScript library for building user interfaces.

  • Vue.js photo Vue.js

    🖖 Vue.js is a progressive, incrementally-adoptable JavaScript framework for building UI on the web.

  • Typescript photo Typescript

    TypeScript is a superset of JavaScript that compiles to clean JavaScript output.

  • TensorFlow photo TensorFlow

    An Open Source Machine Learning Framework for Everyone

  • Django photo Django

    The Web framework for perfectionists with deadlines.

  • D3 photo D3

    Bring data to life with SVG, Canvas and HTML. 📊📈🎉

Recommend Topics

  • javascript

    JavaScript (JS) is a lightweight interpreted programming language with first-class functions.

  • web

    Some thing interesting about web. New door for the world.

  • server

    A server is a program made to process requests and deliver data to clients.

  • Machine learning

    Machine learning is a way of modeling and interpreting data that allows a piece of software to respond intelligently.

  • Game

    Some thing interesting about game, make everyone happy.

Recommend Org

  • Facebook photo Facebook

    We are working to build community through open source technology. NB: members must have two-factor auth.

  • Microsoft photo Microsoft

    Open source projects and samples from Microsoft.

  • Google photo Google

    Google ❤️ Open Source for everyone.

  • D3 photo D3

    Data-Driven Documents codes.