简体   繁体   English

如何将数据导出到 Excel 文件

[英]How can I export data to an Excel file

I have an Excel file with data in it.我有一个包含数据的 Excel 文件。 I want to write some specific rows of it to another Excel file that I created by code.我想将它的一些特定行写入我通过代码创建的另一个 Excel 文件。 By the way I have the indexes of these rows in a list.顺便说一下,我在列表中列出了这些行的索引。 How can i do that?我怎样才能做到这一点?

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

This can read+write MS Office files (including Excel)...这可以读写 MS Office 文件(包括 Excel)...

Another option see http://www.codeproject.com/KB/office/OpenXML.aspx另一种选择见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...如果您需要更多像渲染、公式等,那么有不同的商业库,如 Aspose 和 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.上面的代码是直接从csharp.net 上下来的,请在网站上查看。

I used interop to open Excel and to modify the column widths once the data was done.我使用互操作打开 Excel 并在数据完成后修改列宽。 If you use interop to spit the data into a new Excel workbook (if this is what you want), it will be terribly slow.如果您使用互操作将数据吐到新的 Excel 工作簿中(如果这是您想要的),它会非常慢。 Instead, I generated a .CSV , then opened the .CSV in Excel.相反,我生成了一个.CSV ,然后在 Excel 中打开了.CSV This has its own problems, but I've found this the quickest method.这有其自身的问题,但我发现这是最快的方法。

First, convert the .CSV :首先,转换.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:然后,将其导出到 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;

    // iterate over 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."右键单击解决方案资源管理器中的解决方案,然后选择“管理 NuGet 包”。 - add Microsoft.Office.Interop.Excel - 添加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.在新建 > 项目下,选择 Visual C# > Windows 桌面 > 控制台应用程序。 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;

Have you ever hear NPOI, a .NET library that can read/write Office formats without Microsoft Office installed.你有没有听说过 NPOI,一个 .NET 库,可以在没有安装 Microsoft Office 的情况下读/写 Office 格式。 No COM+, no interop.没有 COM+,没有互操作。 Github Page Github 页面

This is my Excel Export class这是我的 Excel 导出类

/*
 * User: TMPCSigit aswzen@gmail.com
 * Date: 25/11/2019
 * Time: 11:28
 * 
 */
using System;
using System.IO;
using System.Text.RegularExpressions;
using System.Windows.Forms;

using NPOI.HSSF.UserModel;
using NPOI.SS.UserModel;
using NPOI.XSSF.UserModel;

namespace Employee_Manager
{
    public static class ExportHelper
    {       
        public static void WriteCell( ISheet sheet, int columnIndex, int rowIndex, string value )
        {
            var row = sheet.GetRow( rowIndex ) ?? sheet.CreateRow( rowIndex );
            var cell = row.GetCell( columnIndex ) ?? row.CreateCell( columnIndex );

            cell.SetCellValue( value );
        }
        public static void WriteCell( ISheet sheet, int columnIndex, int rowIndex, double value )
        {
            var row = sheet.GetRow( rowIndex ) ?? sheet.CreateRow( rowIndex );
            var cell = row.GetCell( columnIndex ) ?? row.CreateCell( columnIndex );

            cell.SetCellValue( value );
        }
        public static void WriteCell( ISheet sheet, int columnIndex, int rowIndex, DateTime value )
        {
            var row = sheet.GetRow( rowIndex ) ?? sheet.CreateRow( rowIndex );
            var cell = row.GetCell( columnIndex ) ?? row.CreateCell( columnIndex );

            cell.SetCellValue( value );
        }
        public static void WriteStyle( ISheet sheet, int columnIndex, int rowIndex, ICellStyle style )
        {
            var row = sheet.GetRow( rowIndex ) ?? sheet.CreateRow( rowIndex );
            var cell = row.GetCell( columnIndex ) ?? row.CreateCell( columnIndex );

            cell.CellStyle = style;
        }

        public static IWorkbook CreateNewBook( string filePath )
        {
            IWorkbook book;
            var extension = Path.GetExtension( filePath );

            // HSSF => Microsoft Excel(xls形式)(excel 97-2003)
            // XSSF => Office Open XML Workbook形式(xlsx形式)(excel 2007以降)
            if( extension == ".xls" ) {
                book = new HSSFWorkbook();
            }
            else if( extension == ".xlsx" ) {
                book = new XSSFWorkbook();
            }
            else {
                throw new ApplicationException( "CreateNewBook: invalid extension" );
            }

            return book;
        }
        public static void createXls(DataGridView dg){
            try {
                string filePath = "";
                SaveFileDialog sfd = new SaveFileDialog();
                sfd.Filter = "Excel XLS (*.xls)|*.xls";
                sfd.FileName = "Export.xls";
                if (sfd.ShowDialog() == DialogResult.OK)
                {
                    filePath = sfd.FileName;
                    var book = CreateNewBook( filePath );
                    book.CreateSheet( "Employee" );
                    var sheet = book.GetSheet( "Employee" );
                    int columnCount = dg.ColumnCount;
                    string columnNames = "";
                    string[] output = new string[dg.RowCount + 1];
                    for (int i = 0; i < columnCount; i++)
                    {
                        WriteCell( sheet, i, 0, SplitCamelCase(dg.Columns[i].Name.ToString()) );
                    }
                    for (int i = 0; i < dg.RowCount; i++)
                    {
                        for (int j = 0; j < columnCount; j++)
                        {
                            var celData =  dg.Rows[i].Cells[j].Value;
                            if(celData == "" || celData == null){
                                celData = "-";
                            }
                            if(celData.ToString() == "System.Drawing.Bitmap"){
                                celData = "Ada";
                            }
                            WriteCell( sheet, j, i+1, celData.ToString() );
                        }
                    }
                    var style = book.CreateCellStyle();
                    style.DataFormat = book.CreateDataFormat().GetFormat( "yyyy/mm/dd" );
                    WriteStyle( sheet, 0, 4, style );
                    using( var fs = new FileStream( filePath, FileMode.Create ) ) {
                        book.Write( fs );
                    }
                }
            }
            catch( Exception ex ) {
                Console.WriteLine( ex );
            }
        }
        public static string SplitCamelCase(string input)
        {
            return Regex.Replace(input, "(?<=[a-z])([A-Z])", " $1", RegexOptions.Compiled);
        }
    }
}

I was also struggling with a similar issue dealing with exporting data into an Excel spreadsheet using C#.我也在处理使用 C# 将数据导出到 Excel 电子表格的类似问题。 I tried many different methods working with external DLLs and had no luck.我尝试了许多使用外部 DLL 的不同方法,但没有成功。

For the export functionality you do not need to use anything dealing with the external DLLs.对于导出功能,您不需要使用任何处理外部 DLL 的东西。 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.文章讨论了如何使用 ASP.NET 将数据导出到 Excel 电子表格。

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

You can use ExcelDataReader to read existing Excel file:您可以使用ExcelDataReader读取现有的Excel文件:

using (var stream = File.Open("C:\\temp\\input.xlsx", FileMode.Open, FileAccess.Read))
{
    using (var reader = ExcelReaderFactory.CreateReader(stream))
    {
        while (reader.Read())
        {
            for (var i = 0; i < reader.FieldCount; i++)
            {
                var value = reader.GetValue(i)?.ToString();
            }
        }
    }
}

After you collected all data needed you can try my SwiftExcel library to export it to the new Excel file:收集所需的所有数据后,您可以尝试使用我的SwiftExcel库将其导出到新的Excel文件中:

using (var ew = new ExcelWriter("C:\\temp\\output.xlsx"))
{
    for (var i = 1; i < 10; i++)
    {
        ew.Write("your_data", i, 1);
    }
}

Nuget commands to install both libraries:安装两个库的 Nuget 命令:

Install-Package ExcelDataReader安装包 ExcelDataReader

Install-Package SwiftExcel安装包 SwiftExcel

With Aspose.Cells library for .NET, you can easily export data of specific rows and columns from one Excel document to another.使用 .NET 的Aspose.Cells库,您可以轻松地将特定行和列的数据从一个 Excel 文档导出到另一个。 The following code sample shows how to do this in C# language.以下代码示例显示了如何使用 C# 语言执行此操作。

// Open the source excel file.
Workbook srcWorkbook = new Workbook("Source_Workbook.xlsx");

// Create the destination excel file.
Workbook destWorkbook = new Workbook();
   
// Get the first worksheet of the source workbook.
Worksheet srcWorksheet = srcWorkbook.Worksheets[0];

// Get the first worksheet of the destination workbook.
Worksheet desWorksheet = destWorkbook.Worksheets[0];

// Copy the second row of the source Workbook to the first row of destination Workbook.
desWorksheet.Cells.CopyRow(srcWorksheet.Cells, 1, 0);

// Copy the fourth row of the source Workbook to the second row of destination Workbook.
desWorksheet.Cells.CopyRow(srcWorksheet.Cells, 3, 1);

// Save the destination excel file.
destWorkbook.Save("Destination_Workbook.xlsx");

将行数据从一个 Excel 文档复制到另一个

The following blog post explains in detail how to export data from different sources to an Excel document.以下博客文章详细解释了如何将不同来源的数据导出到 Excel 文档。
https://blog.conholdate.com/2020/08/10/export-data-to-excel-in-csharp/ https://blog.conholdate.com/2020/08/10/export-data-to-excel-in-csharp/

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM