How can I export data to an Excel file

≯℡__Kan透↙ 提交于 2019-11-27 20:11:21
Yahia

MS provides the OpenXML SDK V 2.5 - see https://msdn.microsoft.com/en-us/library/bb448854(v=office.15).aspx

This can read+write MS Office files (including Excel)...

Another option see http://www.codeproject.com/KB/office/OpenXML.aspx

IF you need more like rendering, formulas etc. then there are different commercial libraries like Aspose and Flexcel...

 private void button1_Click(object sender, EventArgs e)
    {
        Excel.Application xlApp ;
        Excel.Workbook xlWorkBook ;
        Excel.Worksheet xlWorkSheet ;
        object misValue = System.Reflection.Missing.Value;

        xlApp = new Excel.ApplicationClass();
        xlWorkBook = xlApp.Workbooks.Add(misValue);

        xlWorkSheet = (Excel.Worksheet)xlWorkBook.Worksheets.get_Item(1);
        xlWorkSheet.Cells[1, 1] = "http://csharp.net-informations.com";

        xlWorkBook.SaveAs("csharp-Excel.xls", Excel.XlFileFormat.xlWorkbookNormal, misValue, misValue, misValue, misValue, Excel.XlSaveAsAccessMode.xlExclusive, misValue, misValue, misValue, misValue, misValue);
        xlWorkBook.Close(true, misValue, misValue);
        xlApp.Quit();

        releaseObject(xlWorkSheet);
        releaseObject(xlWorkBook);
        releaseObject(xlApp);

        MessageBox.Show("Excel file created , you can find the file c:\\csharp-Excel.xls");
    }

    private void releaseObject(object obj)
    {
        try
        {
            System.Runtime.InteropServices.Marshal.ReleaseComObject(obj);
            obj = null;
        }
        catch (Exception ex)
        {
            obj = null;
            MessageBox.Show("Exception Occured while releasing object " + ex.ToString());
        }
        finally
        {
            GC.Collect();
        }
    }

The above code is taken directly off csharp.net please take a look on the site.

I used interop to open Excel and to modify the column widths once the data was done. If you use interop to spit the data into a new Excel workbook (if this is what you want), it will be terribly slow. Instead, I generated a CSV, then opened the CSV in Excel. This has its own problems, but I've found this the quickest method.

First, convert the CSV:

        // Convert array data into CSV format.
        // Modified from http://csharphelper.com/blog/2018/04/write-a-csv-file-from-an-array-in-c/.
        private string GetCSV(List<string> Headers, List<List<double>> Data)
        {
            // Get the bounds.
            var rows = Data[0].Count;
            var cols = Data.Count;
            var row = 0;


            // Convert the array into a CSV string.
            StringBuilder sb = new StringBuilder();

            // Add the first field in this row.
            sb.Append(Headers[0]);

            // Add the other fields in this row separated by commas.
            for (int col = 1; col < cols; col++)
                sb.Append("," + Headers[col]);

            // Move to the next line.
            sb.AppendLine();

            for (row = 0; row < rows; row++)
            {
                // Add the first field in this row.
                sb.Append(Data[0][row]);

                // Add the other fields in this row separated by commas.
                for (int col = 1; col < cols; col++)
                    sb.Append("," + Data[col][row]);

                // Move to the next line.
                sb.AppendLine();
            }

            // Return the CSV format string.
            return sb.ToString();
        }

Then, Export it to Excel!

    public void ExportToExcel()
    {

        // Initialize app and pop Excel on the screen.
        var excelApp = new Excel.Application
        {
            Visible = true
        };

        // I use unix time to give the files a unique name that's almost somewhat useful.
        DateTime dateTime = DateTime.UtcNow;
        long unixTime = ((DateTimeOffset)dateTime).ToUnixTimeSeconds();
        var path = @"C:\Users\my\path\here + unixTime + ".csv";

        var csv = GetCSV();
        File.WriteAllText(path, csv);
        // Create a new workbook and get its active sheet.
        excelApp.Workbooks.Open(path);

        var workSheet = (Excel.Worksheet)excelApp.ActiveSheet;

        // iterrate through each value and throw it in the chart
        for (var column = 0; column < Data.Count; column++)
        {
            ((Excel.Range)workSheet.Columns[column + 1]).AutoFit();
        }

        currentSheet = workSheet;

    }

You'll have to install some stuff, too...

  1. Right click on the solution from solution explorer and select "Manage NuGet Packages." Add Microsoft.Office.Interop.Excel.
  2. It might actually work right now if you created the project the way interop wants you to. If it still doesn't work, I had to create a new project in a different category. Under New > Project, select Visual C# > Windows Desktop > Console App. Otherwise, the interop tools won't work.

In case I forgot anything, here's my 'using' statements:

using System;
using System.Collections.Generic;
using System.IO;
using System.Linq;
using System.Text;
using Excel = Microsoft.Office.Interop.Excel;
Tapan kumar

I was also struggling with a similar issue dealing with exporting data into an Excel spreadsheet using C#. I tried many different methods working with external DLLs and had no luck.

For the export functionality you do not need to use anything dealing with the external DLLs. Instead, just maintain the header and content type of the response.

Here is an article that I found rather helpful. The article talks about how to export data to Excel spreadsheets using ASP.NET.

http://www.icodefor.net/2016/07/export-data-to-excel-sheet-in-asp-dot-net-c-sharp.html

标签
易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!