Vue export to excel

There are plenty of ways to export data to CSV, XLS, TXT, or whichever format we want in Vue.js. One of the most significant advantages of using Vue.js is its compatibility with Vanilla JS libraries. It can perform really well with Vanilla JS libraries without any customization out of the box.

Let’s have a look at how we can export JSON data to Excel (xls) format in Vue.js.

Project setup

First, we need to install an NPM package called export-from-json. We can fire up the terminal and enter the following command:

npm install export-from-json -sCode language: JavaScript (javascript)

After the package and its dependencies are installed, we can now use the library. Now, we’re going to create a helper method to parse the data. I’m going to call it excel-parser.js:

import exportFromJSON from "export-from-json";

export const excelParser = () => {
  function exportDataFromJSON(data, newFileName, fileExportType) {
    if (!data) return;
    try {
      const fileName = newFileName || "exported-data";
      const exportType = exportFromJSON.types[fileExportType || "xls"];
      exportFromJSON({ data, fileName, exportType });
    } catch (e) {
      throw new Error("Parsing failed!");
    }
  }

  return {
    exportDataFromJSON
  };
};
Code language: JavaScript (javascript)

As we can see, we first imported the library at line 1. We’ve then created a closure named exportDataFromJSON. Of course, we can call it whatever we want.

We’ve then passed three parameters to it:

  • data: The JSON data (Array) which we need to parse
  • newFileName: We can pass a file name to it by generating a random file name if we want. Or we’ll just use ‘export-data’ name by default in case nothing is passed.
  • fileExportType: Here we can pass the export file type (xls, csv, txt, HTML, etc).

We’ve finally called exportFromJSON at line 9 which generates the required file.

Here’s the sample-data.js file content. Of course, in a real-world scenario, we’re more likely to fetch some data from a remote server instead.

export const sampleData = [
  { id: 1, name: "Night", email: "nightprogrammer95@gmail.com" },
  { id: 2, name: "Gautam", email: "mailgautam@test.com" },
  { id: 3, name: "Alex", email: "xalex@testmail.com" },
  { id: 4, name: "Lina", email: "lina@mail.com" },
  { id: 5, name: "Peter", email: "peter.me@test.com" }
];

Code language: JavaScript (javascript)

And here we have the component (App.vue) to use the above helper:

<template>
  <div id="app">
    <h2>Export data to Excel example in Vue.js</h2>
    <button @click="exportData">Download file</button>
    <div class="np-credits">wwww.nightprogrammer.com</div>
  </div>
</template>

<script>
import { excelParser } from "./excel-parser";
import { sampleData } from "./sample-data";

export default {
  name: "App",
  data() {
    return {
      listData: sampleData,
    };
  },
  methods: {
    exportData() {
      excelParser().exportDataFromJSON(this.listData, null, null);
    },
  },
};
</script>
Code language: HTML, XML (xml)

In the above file, we’ve first imported the sample data and excelParser helper we just created.

We’ve then stored the sample data in the listData state. Finally, we’ve called the exportData method (line 21) on the button click on line 4.

Demo

Here’s what it should look like:

You can find a working version of the above code from my repos here:

Codesandbox / Demo | Github

Vuejs Application JSON To Excel Generation

In this article, we will explore JSON data to excel file generation in the Vuejs application.

An Overview On vue-json-excel:

The technique to download your JSON data as an excel file directly from the browser. The following are key options for the excel vue component.

  • data: The array of data to be exported.
  • fields: Fields inside the JSON object that you want to export. If none provided, all properties in the JSON will be exported.
  • type: Mime type[xls, csv].
  • name: Filename to export.
  • header: Title(s) for the data. Can be a string(one title) or an array of string (multiple titles).
  • footer: Footer(s) for the data. Can be a string(one footer) or an array of strings(multiple footers).
  • default-value: Use as a fallback when the row has no field values.
  • worksheet: Name of the worksheet tab.
  • fetch: Callback to fetch data before download if it’s set it runs immediately function after mouse pressed and before the download process(Note: Only works if no data prop is defined).
  • before-generate: Callback to call a method right before the generate/fetch data(eg: shows loading progress).
  • before-finish: Callback to call a method right before the download box pops out(eg: hiding loading progress).

Unavoidable Excel Warning Popup:

The method implemented in this component uses HTML tables to draw the .xls files, Microsoft Excel no longer recognizes HTML as native content so a warning message will be displayed before opening the file. The content will be rendered perfectly but the message can’t be avoided.

Create A VueJS Sample App:

Command To Install Vue CLI Globally On Your System:
npm run -g @vue/cli
Command To Create Vue App:
vue create your_application_name

After creating a sample application run the following command to start the application.

Command To Run Vue App:
npm run serve

Install vue-json-excel Npm Package:

Command To Install Excel Package:
npm install vue-json-excel

After successful installation package reference will be added to the package.json file.

Global Registration:

Now let’s register our excel plugin in main.js(entry file)

src/main.js:

import Vue from 'vue'
import App from './App.vue'
import JsonExcel from "vue-json-excel";

Vue.component("downloadExcel", JsonExcel);

Vue.config.productionTip = false

new Vue({
  render: h => h(App),
}).$mount('#app')
  • (Line: 3) Imported ‘vue-json-excel’ plugin library.
  • (Line: 5) Registered json excel component to ‘Vue’ instance.

Excel With Simple Example:

Let’s now implement a simple example to import JSON object to excel.

src/components/HelloWorld.Vue:(Html Part)

<template>
  <div>
    <download-excel :data="json_data">
      <button type="button" class="btn btn-success">Download Excel</button>
    </download-excel>
  </div>
</template>
  • Rendered ‘download-excel’ component.
  • (Line: 3) The ‘data’ property takes an array of objects(JSON data exported to excel).

src/components/HelloWorld.Vue:(Script Part)

data() {
return {
 json_data: [
   {
     name: "naveen"
    }
 ]
};
}

field Property:

The ‘field’ property takes a javascript object as input. The ‘field’ property can configure with only required columns from the JSON object to import into an excel sheet. By default, JSON object properties will be taken as heading for the excel column, but while mapping the JSON object properties to ‘field’ object we can change the heading names.

src/components/HelloWorld.vue:

<download-excel 
:data="json_data"
:fields="json_fields">
  <button type="button" class="btn btn-success">Download Excel</button>
</download-excel>
  • (Line: 3) Configured ‘fields’ option.d

src/components/HelloWorld.vue:

data() {
 return {
  json_fields:{
	"My Friends Name":"name",
	"Designation":"job"
  },
  json_data: [
	{
	  name: "naveen",
	  job: ".net developer",
	  experience: 5
	}
  ]
 };
}

The ‘json_data’ object contains props like ‘name’, ‘job’, ‘experience’ but only configured ‘name’, ‘job’ properties with ‘json_fields’ object . The «My Friends Name», «Designation» props in ‘fields’ object will be taken as column heading in the excel.

name Property:

The ‘name’ property to define the filename. By default plugin uses excel name as ‘data’.

src/components/HelloWorld.vue:(Html Part)

<download-excel 
:data="json_data"
:fields="json_fields"
:name="fileName">
  <button type="button" class="btn btn-success">Download Excel</button>
</download-excel>

(Line: 4) The ‘name’ property defined.

src/components/HelloWorld.vue:(Script Part)

data() {
 return{
  fileName:"my-friends-data",
 };
}

header And footer Properties:

The ‘header’ and ‘footer’ props can define for excel.

src/components/HelloWorld.vue:(Html Part)

<download-excel 
:data="json_data"
:fields="json_fields"
:name="fileName"
:header="header"
:footer="footer">
  <button type="button" class="btn btn-success">Download Excel</button>
</download-excel>

src/components/HelloWorld.vue:(Script Part)

data() {
 return {
  header:"Welcome!",
  footer:"Good bye",
 };
}

fetch Property:

In case you need to fetch data from the server, you could use the fetch prop that allows you to define a callback function that is executed when your user clicks the download button. If you use the ‘fetch’ property then you should not use the ‘data’ property.

src/components/HelloWorld.vue:

<download-excel 
:fetch="fetchTodos">
  <button type="button" class="btn btn-success">Download Excel</button>
</download-excel>
  • (Line: 2) The ‘fetch’ property assigned with callback function ‘fetchTodos’

src/components/HelloWorld.vue:

methods:{
async fetchTodos(){
  const response = await axios.get('https://jsonplaceholder.typicode.com/users/1/todos');
  return response.data;
}
}
  • The ‘fetchTodos’ callback method invokes ‘Todos'(test endpoint).

before-generate And before-finish Properties:

The ‘before-generate’ property takes a callback function. This property can be used to write login for loading message while ‘fetch’ property invoking API and reading the JSON data.

The ‘before-finish’ property takes a callback function. This property to dispose of the loading message or notify that API invoked by the ‘fetch’ callback function completed.

src/components/HelloWorld.vue:(Html Part)

<download-excel 
:fetch="fetchTodos"
:before-generate="beforeGenerate"
:before-finish="beforeFinish">
  <button type="button" class="btn btn-success">Download Excel</button>
</download-excel>

src/components/HelloWorld.vue:(Script Part)

methods:{
async fetchTodos(){
  const response = await axios.get('https://jsonplaceholder.typicode.com/users/1/todos');
  return response.data;
},
beforeGenerate(){
  alert('loading')
},
beforeFinish(){
  alert('close')
}
}

That’s all about some of the key options to configure the JSON to Excel generation Vuejs application. To explore more configuration and options check at «https://github.com/jecovier/vue-json-excel».

Support Me!

Buy Me A Coffee
PayPal Me

Wrapping Up:

Hopefully, I think this article delivered some useful information on the JSON to Excel generation in the Vuejs application. I love to have your feedback, suggestions, and better techniques in the comment section below.

Follow Me:

In this article, we will learn about how to export excel using Vue.js in Kendo Grid. Kendo Grid is one of the most widely used plugin for creating the data grid, so we almost we have the functionality for exporting the excel, we can achieve that easily with this plugin.

Export Excel:

Step 1: Install the following packages in vue.js:

npm install @progress/kendo-vue-excel-export
npm install @progress/kendo-vue-grid

Step 2: Open Export_Excel.vue and add the following in it:

<template>
<div>
    <button @click="exportExcel" class="k-button">Export Excel</button>
    <Grid
        :style="{height: '280px'}"
        :data-items="items"
        :columns = "columns">
    </Grid>
</div>
</template>
<script>
import { Grid } from '@progress/kendo-vue-grid';
import { saveExcel } from '@progress/kendo-vue-excel-export';

export default {
    components: {
        'Grid': Grid
    },
   data: function () {
        return {
            items: [],
            columns: [
                { field: 'ProductID'},
                { field: 'ProductName', title: 'Product Name' },
                { field: 'UnitPrice', title: 'Unit Price' }
            ]
        };
    },
    methods: {
        exportExcel () {
            saveExcel({
                data: this.items,
                fileName: "myFile",
                columns: [
                  { field: 'ProductID'},
                  { field: 'ProductName', title: 'Product Name' }
              ]
            });
        },
        createRandomData(count) {
            const productNames = ['Chai', 'Chang', 'Syrup', 'Apple', 'Orange', 'Banana', 'Lemon', 'Pineapple', 'Tea', 'Milk'];
            const unitPrices = [12.5, 10.1, 5.3, 7, 22.53, 16.22, 20, 50, 100, 120]

            return Array(count).fill({}).map((_, idx) => ({
                ProductID: idx + 1,
                ProductName: productNames[Math.floor(Math.random() * productNames.length)],
                UnitPrice: unitPrices[Math.floor(Math.random() * unitPrices.length)]
            }));
        }
    },
    mounted() {
        this.items = this.createRandomData(100);
    }
};
</script>
<style scoped>
.k-button {
    margin-top: 10px;
    margin-bottom: 10px;
}
</style>

Code in action:

Содержание

  1. leduyptit/vue-export-excel
  2. Sign In Required
  3. Launching GitHub Desktop
  4. Launching GitHub Desktop
  5. Launching Xcode
  6. Launching Visual Studio Code
  7. Latest commit
  8. Git stats
  9. Files
  10. README.md
  11. Fetch Example
  12. Vue export to excel
  13. How to Import and Export Excel XLSX Using Vue
  14. The Vue App
  15. Vue Application Structure
  16. Adding SpreadJS to your Vue App
  17. Adding Excel Export
  18. Adding Excel Import
  19. Testing Your Vue App
  20. Conclusion

leduyptit/vue-export-excel

Use Git or checkout with SVN using the web URL.

Work fast with our official CLI. Learn more.

Sign In Required

Please sign in to use Codespaces.

Launching GitHub Desktop

If nothing happens, download GitHub Desktop and try again.

Launching GitHub Desktop

If nothing happens, download GitHub Desktop and try again.

Launching Xcode

If nothing happens, download Xcode and try again.

Launching Visual Studio Code

Your codespace will open once ready.

There was a problem preparing your codespace, please try again.

Latest commit

Git stats

Files

Failed to load latest commit information.

README.md

JSON to Excel for VUE 2

Download your JSON data as an excel file directly from the browser. This component it’s based on the solution proposed on this thread https://stackoverflow.com/questions/17142427/javascript-to-export-html-table-to-excel

Important! Extra prompt in Microsoft Excel

The method implemented in this component use HTML tables to draw the .xls files, Microsoft Excel no longer recognize HTML as native content so will prompt a warning message before open the file. The content will be rendered perfectly but the message can’t be avoid.

Get the package:

Register JsonExcel in your app entrypoint:

In your template

Name Type Description
data Array Data to be exported
fields Object fields inside the Json Object that you want to export. If no given, all the properties in the Json are exported
export-fields (exportFields) Object this prop is used to fix the problem with other components that use the variable fields, like vee-validate. exportFields works exactly like fields
type string mime type [xls, csv], default: xls
name string filename to export, deault: data.xls
title string/Array Title(s) for the data, could be a string or an array of strings (multiple titles)
footer string/Array Footer(s) for the data, could be a string or an array of strings (multiple footers)
default-value (defaultValue) string Use as fallback when the row has no field values, default: »
worksheet string Name of the worksheet tab. default: ‘Sheet1’
fetch Function Callback to fetch data before download, if it’s set it runs immediately after mouse pressed and before download process. IMPORTANT: only works if no data prop is defined
before-generate Function Callback to call a method right before the generate / fetch data, eg:show loading progress
before-finish Function Callback to call a method right before the download box pops out, eg:hide loading progress

In your HTML call it like

  • json_data: Contains the data you want to export,
  • json_fields: You can select what fields to export, especify nested data and assign labels to the fields the key is the label, the value is the JSON field. This will export the field data ‘as is’. If you need to customize the the exported data you can define a callback function. Thanks to @gucastiliao.

To export JSON to CSV file just add the prop type with value «csv»:

Multi-line values will appear in a single cell in Excel

A single text value in the data that contains newline characters will appear as a single cell in Excel. This avoids the undesired behavior of multi-line values getting split into multiple cells that must be merged before using data filters and pivot tables.

Fetch Data on Demand

In case you need to fetch data from the server, you could use the fetch prop that allows you to define a callback function that is executed when your user click the download button. This function has to return a json value containing the data to export. A basic use case is:

Fetch Example

when using callbacks function in the fields description, you have three option to retrieve data:

  • field: ‘path.to.nested.property’ you can retrieve an especific value using the nested property notation.
  • field: ‘define.nested.object’ you can retrieve an nested object too
  • Or get the whole row if field it’s undefined.

This project is in an early stage of development. Any contribution is welcome 😀

Источник

Vue export to excel

JSON to Excel for VUE 2

Download your JSON data as an excel file directly from the browser. This component it’s based on the solution proposed on this thread https://stackoverflow.com/questions/17142427/javascript-to-export-html-table-to-excel

Important! Extra prompt in Microsoft Excel

The method implemented in this component use HTML tables to draw the .xls files, Microsoft Excel no longer recognize HTML as native content so will prompt a warning message before open the file. The content will be rendered perfectly but the message can’t be avoid.

Get the package:

Register excel in your app entrypoint:

In your template

Name Type Description
data Array Data to be exported
fields Object fields inside the Json Object that you want to export. If no given, all the properties in the Json are exported
export-fields (exportFields) Object this prop is used to fix the problem with other components that use the variable fields, like vee-validate. exportFields works exactly like fields
type string mime type [xls, csv], default: xls
name string filename to export, deault: data.xls
title string/Array Title(s) for the data, could be a string or an array of strings (multiple titles)
footer string/Array Footer(s) for the data, could be a string or an array of strings (multiple footers)
default-value (defaultValue) string Use as fallback when the row has no field values, default: »
worksheet string Name of the worksheet tab. default: ‘Sheet1’
fetch Function Callback to fetch data before download, if it’s set it runs immediately after mouse pressed and before download process. IMPORTANT: only works if no data prop is defined
before-generate Function Callback to call a method right before the generate / fetch data, eg:show loading progress
before-finish Function Callback to call a method right before the download box pops out, eg:hide loading progress

In your HTML call it like

  • json_data: Contains the data you want to export,
  • json_fields: You can select what fields to export, especify nested data and assign labels to the fields the key is the label, the value is the JSON field. This will export the field data ‘as is’. If you need to customize the the exported data you can define a callback function. Thanks to @gucastiliao.

To export JSON to CSV file just add the prop type with value «csv»:

This project is in an early stage of development. Any contribution is welcome 😀

Источник

How to Import and Export Excel XLSX Using Vue

“It looks great, but could you just add Excel import?”

If you’ve developed software for a long time, you’ve probably heard that question from a manager more than once. To a non-technical crowd, asking for Excel import/export doesn’t sound like a big deal. How hard could it be, right?

But all too often, this question strikes fear into the hearts of developers. On most platforms, working with Excel files requires lots of work. Historically, this has been doubly true on the web. Working with Excel data in a web app has felt a bit like this xkcd comic: «It can be hard to explain the difference between the easy and the virtually impossible.» Building your own in-browser spreadsheet with Excel import and Excel export feels like a problem that will take five years and a research team to solve.

That’s changing. We now have turnkey libraries that let you drop a fully-functioning spreadsheet into your web app. SpreadJS is one of them. We’ll look at how to take an existing Vue app – a real-world app using a Vuex store – and enhance it using SpreadJS.

The rest of the article assumes that you already understand HTML, CSS, and JavaScript. It also assumes you have a working knowledge of the Vue.js progressive JavaScript framework for creating web UI. It will help if you’ve used Vuex for state management, but don’t worry if you haven’t. It’s intuitive and easy to understand, and you’ll be able to figure out what’s going on just by reading the code if you’ve used Vue.

Want to test exporting Excel in JavaScipt Frameworks? Download Now!

In this blog, we will cover how to add Excel Import and Export to your Vue App following these steps:

The Vue App

The Vue app we’ll be working on is a straightforward sales dashboard with a few summary panels and a table of data. It’s the kind of app that falls into the “not bad” category:

Although it’s just a demo, it’s exactly the kind of app that enterprise web developers have to create. It’s also exactly the kind of app that we’re typically asked to add Excel functionality to, so it will be a perfect example for the rest of this article.

The code for this application can be found here.

To set the stage: the dashboard is a single-page application made with Vue. It’s using the latest and greatest Vue best practices: single-file components and a Vuex data store. It’s also using Bootstrap for its CSS components and grid system.

Bootstrap isn’t as popular as it used to be. But in reality, Bootstrap is still everywhere – especially in enterprise web apps where Excel support is usually needed. I’d wager that plenty of new enterprise web apps will still use Bootstrap in 2030.

If you’d rather use Bulma or Tachyons in your spreadsheet-enabled apps, go right ahead! SpreadJS will work happily with either of them.

Vue Application Structure

Let’s take a look at how the code is structured. Our Vuex store and Vue application are both defined in main.js. We have several single-file Vue components, all located in the components folder.
If you look at our Vuex store, you’ll see the following:

Our store’s initial state is set to the value of recentSales, a set of dummy data we imported. We also have a function that handles updating the recent sales when they are changed.

Wait a minute – if we’ve only got one set of data, how are we generating three charts and a table? To see what’s happening, open up the Dashboard.vue component. In it, you’ll see several computed properties are being generated based on the data in the Vuex store:

Now it makes more sense! The single data set contains everything we need to generate all of the numbers and tables for our dashboard. Since the data is in a reactive Vuex store, if the data updates, then all of the dashboard panels will update automatically.

This reactivity will come in handy in the next section when we replace our boring old static table with an editable spreadsheet.

Adding SpreadJS to your Vue App

Here’s where the fun starts! We have our dashboard, but we want to eliminate that clunky old HTML table. So, we’ll have to change things up a little bit. We have a great starting point, but we must run our app locally to use SpreadJS in development mode without a license.

You can download the finished code here to see the final result.

Start by opening the original project without SpreadJS, open a terminal, navigate to the directory where you cloned the repository, and run ‘npm install’. This installs the dependencies needed to run the application. When the dependency installation finishes, run ‘npm serve’ to see the updated app in action. If you want to specifically import the libraries used, you can use this command:

Let’s walk through the changes we’ll have to make to upgrade our old app to its new and improved version. Since we’re going to replace our sales table with a spreadsheet, we will put the sheet into our existing SalesTable.vue component. But first, we’ll have to get rid of our old table. Once it is gone, our SalesTable template will look like this:

After eliminating the table, we’ve got our table panel ready and waiting for a spreadsheet, so let’s add one! After adding a SpreadJS sheet, our template will look like this:

That’s a lot to take in, so let’s walk through it to understand what is happening.

First, we create a spreadsheet by using the gc-spread-sheets element and binding it to two of our component’s properties: hostClass and workbookInit.

Inside the spreadsheet, we create a new worksheet with the gc-worksheet element and bind it to our component’s tableData and autoGenerateColumns properties. Note that tableData is exactly the same tableData we used to generate our plain HTML table. We can put our data into SpreadJS as-is with no changes required!

Finally, inside the worksheet, we define columns that tell SpreadJS how to display our data. The dataField property tells us which property of the underlying dataset this column should display, and headerText gives SpreadJS a nicely-formatted column name to use. The rest of the bindings for each column are straightforward; the SpreadJS documentation has a complete list of everything you can pass to a gc-column.

So, with our template in place, how much code will be needed to make this all work? Fortunately, not much at all! Here’s our SalesTable.vue component’s new script code:

Due to Vue’s simplicity, it takes very little code to make this work. If there’s anything here you’re unfamiliar with, the ‘Components In-depth’ section of the Vue documentation explains Vue components in detail. The only things that have changed from before are a few imports, some data properties, and a couple of methods. The data properties should look familiar; we saw them a moment ago in the template. They’re configuration options we are binding to the components in our SpreadJS spreadsheet.

The workbookInit method is a callback that SpreadJS calls when the sheet is initialized. In this method, we save our SheetJS spreadsheet object as an instance variable on our component so we can interact with it directly if necessary. We also added a binding function for the ValueChanged event to automatically update data whenever values are changed in the SpreadJS instance.

One last change: we give our component a scoped style to help the spreadsheet style itself. We saw this earlier when we passed the hostClass to the gc-spread-sheets element. Since hostClass is set to ‘spreadsheet’, we’re going to create a CSS class named spreadsheet:

And at this point, if we make no other changes and load our Dashboard, it will look like this:

But wait, there’s more!

Remember how we passed our table data to the spreadsheet without making any changes to the data set? Now that our data is in a spreadsheet, we can edit it.

What will happen if we change the value of sale #6 from $35,000 to $3500? If we go into the sheet and edit the value, we get a dashboard that looks like this:

Wow! What happened?

We updated the SpreadJS sheet, and it automatically updated our Vuex store.

It also looks like Angela went from having a spectacular sales month to having a mediocre one. Sorry about that, Angela!

We now have an enhanced dashboard that a manager would be happy with. They can modify the data and watch the dashboard update before their eyes. But we can do even better by adding the ability to import and export Excel files. Next, we’ll learn how to do that.

Adding Excel Export

Adding Excel export to our sheet is easy. First, let’s add an export button to our dashboard. We’re going to place it at the bottom of our table panel in the SalesTable.vue file, right after the gc-spread-sheets closing tag:

As you can see, our button is expecting a click handler named exportSheet. We’ll add it in a moment, but first, we’re we will import a function from an NPM package named file-saver:

Next, let’s add exportSheet to our component’s methods object:

Here’s what the code is doing: first, we get a reference to our Sales Data sheet. Since it’s the only sheet in our spreadsheet, it lives at index 0, and we access it by calling getSheet. This can be used elsewhere in the function should we need to interact directly with the sheet.

We then instantiate SpreadJS’ ExcelIO library, convert our sheet to JSON, and ask SpreadJS to save it. And voila! We’ve exported an Excel file from our spreadsheet-enabled Vue app!

Note that we’re passing two serialization options to the sheet’s toJSON call: includeBindingSource and columnHeadersAsFrozenRows. Together, these options ensure that the data we bound to the sheet is exported correctly and that the sheet contains our column headers. So, looking at the exported Excel file will understand each column.

Adding Excel Import

Next, it’s time to add the ability to import Excel files.
Right below our export button, we’re going to add the following bit of markup:

As you can see, we will use a standard HTML file picker and trigger a component method named fileChange when a file is selected.

Now that we’ve added the template, let’s add the change handler to our component’s methods object:

Importing an Excel file is much the same as exporting it, except in reverse. After a file is chosen, we ask ExcelIO to import it. When done, it passes the sheet information to a callback function as a JavaScript object. Next, we pass the imported data through a custom function to extract the data we need from it and then commit it back to the Vuex store.

Typically, importing a file is as simple as calling that ExcelIO open method but using the workbook “fromJSON” method. In this case, we just want to parse the data from the imported file and update the store, which will then update SpreadJS.

In our extractSheetData function — which you’ll find in the src/util.util.js file — you’ll see that we pull data out of the JavaScript object returned by ExcelIO and restructure it to match the shape of the data in our Vuex store.

Our import function assumes that the data in the imported sheet will have the same columns as our original data set. If someone uploads a spreadsheet that doesn’t meet this requirement, our app won’t be able to handle it. This is an acceptable limitation in most line-of-business apps. Since our dashboard is designed to display a specific data type, it’s reasonable to ask users to supply data in the format the app expects.

When data extraction is complete, we call commit on the Vuex store and send the updated sales transaction data. The SpreadJS sheet and the dashboard panels then update themselves to reflect the new data. We can actually use a different mutation function for importing versus a value being changed so that we can add that to the main.js file as “IMPORT_RECENT_SALES”:

Testing Your Vue App

Now that you have seen the code let’s test out Excel import and export in our Vue app.

Start by clicking the ‘Export to Excel’ button. Your web browser will then download an Excel spreadsheet containing all of the data we saw in our dashboard’s spreadsheet.
Open the sheet in Excel and add a couple of lines of data. It’s okay if you use new countries or new salespeople; all our dashboard components can handle it. Just be careful not to change the column order or names. When you’re finished, click the ‘Choose File’ button at the bottom of the Recent Sales panel. Select the Excel file you just edited.

When you select the file, you’ll see the updated dashboard components.

Conclusion

We’re done! We took an ordinary Vue dashboard app and added a live spreadsheet to it. We can now edit the data in the sheet and watch our entire dashboard update itself. Our enhanced dashboard is also able to import and export Excel files.
Vue, Vuex, and SpreadJS complement each other well. With Vue’s easy templating and data binding, Vuex’s reactive data store, and SpreadJS’ interactive spreadsheets, complex enterprise JavaScript apps can be created in hours.

As great as this might seem, we’ve barely scratched the surface of what SpreadJS can do. To better understand what SpreadJS can do for you, refer to the SpreadJS Demos, which include full demos of the different features of SpreadJS, including explanations as well as live code showcasing those features. If you’re looking to dive deeper into using SpreadJS in your own apps, the SpreadJS Documentation has the information you need.

In another article series, we demonstrate how to export Excel in other JavaScript frameworks:

Want to test exporting Excel in JavaScipt Frameworks? Download Now!

Источник

Small knowledge, big challenge! This article is participating in the creation activity of «Essential Tips for Programmers».

A journey of a thousand miles begins with single step

background

Prior to this article have two articles about the Vue export excel file, use Vue Export2Excel export excel file and Vue Sheet are derived using Export2MultipleSheetExcel excel file. This article introduces how to export general tables as Excel files and multi-sheet Excel files respectively, so why do we need this article? The answer must be that neither approach meets current business needs.

Such as below

Train of thought

The table above has no header (business requirements must be presented as such), and there are various cells that need to be merged, making exporting such a table really tricky as the previous article suggested. But let’s think differently. This table has been displayed. Can we directly take out the data from the DOM node of this table and put it into Excel? Indeed, the following approach is just that, and can be exported to Excel files without having to worry about table formats (like cell merging, or whether cells can be edited)

use

This article needs to proceed on the basis of the above, if you have not read the above, you need to install the following dependency packages first, if already installed, please skip.

# use npm
npm install file-saver -S
npm install xlsx -S
npm install script-loader -D

# use yarn
yarn add file-saver xlsx
yarn add file-saver script-loader --dev
Copy the code

Create a VUE file in your project, configure the route for testing, and use the elementUI component library in your project

In the template

template div class="dom-to-excel" el-button type="primary" @click="exData" /el-button ! el-table :data="tableDataLegacy" id="legacy" border height="800" class="tableListGrid" :span-method="objectSpanMethod" :row-style="TableRowStyleLegacy" el-table-column v-for="(col, index) in fieldListLegacy" :key="index" :prop="col.field" :label="col.label" :width="col.width" align="center" show-overflow-tooltip el-table-column v-for="(childCol, childindex) in col.child" :key="childindex" :prop="childCol.field" :label="childCol.label" align="center" show-overflow-tooltip /el-table-column /el-table-column /el-table /div /templateCopy the code

Import exported methods and required data into script

import XLSX from 'xlsx'
import FileSaver from 'file-saver'
import { data } from '@/views/funs/data'
Copy the code

Define the required data in the data function

mergeListLegacy: [],
fieldListLegacy: [],
tableDataLegacy: []
Copy the code

Define the method corresponding to the binding event in the template in the methods, and complete the export in this method

exData () {
  var wb = XLSX.utils.table_to_book(document.querySelector('#legacy'), { raw: true })
  var wbout = XLSX.write(wb, { bookType: 'xlsx'.bookSST: true.type: 'array' })
  try {
    FileSaver.saveAs(new Blob([wbout], { type: 'application/octet-stream' }), 'Data report. XLSX')}catch (e) {
    if (typeof console! = ='undefined') {
      console.log(e, wbout)
    }
  }
  return wbout
}
Copy the code

In addition to the focus of the export method, the idea of processing the data returned from the back end and how to carry out dynamic merging is also worth savoring. You can view the case in the code case if you need it.

The output looks like this

Case code

XLSX + FileSaver: gitee.com/yunxii/vue-…

Понравилась статья? Поделить с друзьями:
  • Vsto excel c примеры
  • Vsdx конвертер онлайн в word
  • Vsd в word скачать
  • Vpr в excel как это работает
  • Vpn формула в excel