如何将数据导出到Excel文件

时间:2011-07-27 06:13:53

标签: c# file export oledb

我有一个包含数据的Excel文件。我想将它的一些特定行写入我通过代码创建的另一个Excel文件。顺便说一下,我在列表中有这些行的索引。我怎么能这样做?

7 个答案:

答案 0 :(得分:12)

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

这可以读取+写入MS Office文件(包括Excel)......

另一个选项见http://www.codeproject.com/KB/office/OpenXML.aspx

如果您需要更多像渲染,公式等,那么有不同的商业库,如Aspose和Flexcel ......

答案 1 :(得分:5)

 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();
        }
    }

以上代码直接取自csharp.net,请查看网站。

答案 2 :(得分:0)

我也在努力解决使用C#将数据导出到Excel电子表格中的类似问题。我尝试了许多使用外部DLL的不同方法,但没有运气。

对于导出功能,您不需要使用任何处理外部DLL的内容。相反,只需维护响应的标题和内容类型。

这篇文章我觉得很有帮助。本文讨论了如何使用ASP.NET将数据导出到Excel电子表格。

  

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

答案 3 :(得分:0)

我使用 interop 打开Excel并在完成数据后修改列宽。如果您使用interop将数据吐到新的Excel工作簿中(如果需要的话),它将非常慢。相反,我生成了 CSV ,然后在Excel中打开了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();
        }
  

然后,将其导出到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;

    }

您还必须安装一些东西...

  1. 右键单击解决方案资源管理器中的解决方案,然后选择“管理NuGet软件包”。                 添加Microsoft.Office.Interop.Excel。
  2. 如果您以interop希望的方式创建了项目,那么它现在可能实际上可以正常工作。                 如果仍然无法使用,则必须创建一个不同类别的新项目。                 在“新建”>“项目”下,选择“ Visual C#”>“ Windows桌面”>“控制台应用程序”。                 否则,互操作工具将无法工作。

万一我忘记了什么,这是我的“使用中”声明:

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

答案 4 :(得分:0)

您是否曾经听说过NPOI,这是一个.NET库,可以在不安装Microsoft Office的情况下读取/写入Office格式。没有COM +,没有互操作。 Github Page

这是我的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);
        }
    }
}

答案 5 :(得分:0)

您可以使用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();
            }
        }
    }
}

收集了所有需要的数据之后,可以尝试使用我的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命令:

安装包ExcelDataReader

安装软件包SwiftExcel

答案 6 :(得分:0)

借助用于{NET的Aspose.Cells库,您可以轻松地将特定行和列的数据从一个Excel文档导出到另一个。下面的代码示例显示了如何使用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");

Copy Rows Data from one Excel Document to another

以下博客文章详细说明了如何将数据从不同来源导出到Excel文档。
https://blog.conholdate.com/2020/08/10/export-data-to-excel-in-csharp/