简体   繁体   English

使用 C# 将信息从列表写入 Excel 文件

[英]Write info from list to Excel file using C#

In my C# code, I have a list with data that I want to write into an Excel file using Interop.Excel .在我的 C# 代码中,我有一个包含要使用Interop.Excel写入 Excel 文件的数据的列表。

How could I do it?我怎么能做到?

 try
                {
                    xlsApp = new Excel.Application();
                    xlsWorkbook = xlsApp.Workbooks.Add(misValue);
                    xlsWorksheet = (Excel.Worksheet)xlsWorkbook.Sheets[1];

                    // Create the header for Excel file
                    xlsWorksheet.Cells[1, 1] = "The Export Excels Function";
                    Excel.Range range = xlsWorksheet.get_Range("A1", "E1");
                    range.Merge(1);
                    range.Borders.Color = Color.Black.ToArgb();
                    range.Interior.Color = Color.Yellow.ToArgb();
                    #region get connection string from config file
                    int selectedIndex = DbCbx.SelectedIndex;
                    string[] listConnection = ConfigurationManager.AppSettings["listConnection"].Split(',');
                    connectionString = listConnection[selectedIndex];
                    #endregion
                    int i = 3;
                    if(IsOraDB.Checked)
                    {

                        OracleConnection con = new OracleConnection(connectionString);
                        OracleCommand cmdORA = new OracleCommand();
                        cmdORA.CommandText = sqlselect;
                        cmdORA.Connection = con;
                        con.Open();
                        OracleDataReader dr = cmdORA.ExecuteReader();
                        #region set the max of progress
                        // Set Maximum to the total number of files to copy.
                        progress.Maximum = (int)dr.FieldCount;
                        #endregion
                        if (dr.HasRows)
                        {
                            for (int j = 0; j < dr.FieldCount; ++j)
                            {
                                xlsWorksheet.Cells[i, j + 1] = dr.GetName(j);
                            }
                            ++i;
                        }

                        while (dr.Read())
                        {
                            for (int j = 1; j <= dr.FieldCount; ++j)
                                xlsWorksheet.Cells[i, j] = dr.GetValue(j - 1);
                            ++i;
                            progress.PerformStep();
                        }
                    }   
                    else
                    {
                        using SqlConnection conn = new SqlConnection(connectionString);
                        conn.Open();
                        using SqlCommand cmd = new SqlCommand(sqlselect, conn);
                        using SqlDataReader dr = cmd.ExecuteReader();
                        #region set the max of progress
                        // Set Maximum to the total number of files to copy.
                        progress.Maximum = (int)dr.FieldCount;
                        #endregion
                        if (dr.HasRows)
                        {
                            for (int j = 0; j < dr.FieldCount; ++j)
                            {
                                xlsWorksheet.Cells[i, j + 1] = dr.GetName(j);
                            }
                            ++i;
                        }

                        while (dr.Read())
                        {
                            for (int j = 1; j <= dr.FieldCount; ++j)
                                xlsWorksheet.Cells[i, j] = dr.GetValue(j - 1);
                            ++i;
                            progress.PerformStep();
                        }
                    }    
                   
                   

                    range = xlsWorksheet.get_Range("A2", "I" + (i + 2).ToString());
                    range.Columns.AutoFit();

                    xlsWorkbook.SaveAs(fileName, Excel.XlFileFormat.xlWorkbookDefault, misValue, misValue, misValue, misValue,
                        Excel.XlSaveAsAccessMode.xlExclusive, Excel.XlSaveConflictResolution.xlLocalSessionChanges, misValue, misValue, misValue, misValue);
                    xlsWorkbook.Close(true, misValue, misValue);
                    xlsApp.Quit();

                    ReleaseObject(xlsWorksheet);
                    ReleaseObject(xlsWorkbook);
                    ReleaseObject(xlsApp);

                    if (MessageBox.Show("Excel report has been created on your desktop\nWould you like to open it?", "Created Excel report",
                        MessageBoxButtons.YesNo, MessageBoxIcon.Information, MessageBoxDefaultButton.Button2) == DialogResult.Yes)
                    {
                        Process.Start(@"cmd.exe ", @"/c "+fileName);
                    }
                }
                catch (Exception ex)
                {
                    MessageBox.Show("Error creating Excel report: " + ex.Message, "Error", MessageBoxButtons.OK, MessageBoxIcon.Stop);
                }

add reference and using添加引用并使用

 Microsoft.Office.Interop.Excel

code for one sheat:一张纸的代码:

List<string> list = new List<string>();
        object missing = Type.Missing;
        Excel.Application oXL = new Excel.Application();
        oXL.Visible = false;
        Excel.Workbook oWB = oXL.Workbooks.Add(missing);
        string fileName = string.Empty;
        Excel.Worksheet oSheet = oWB.ActiveSheet as Excel.Worksheet;
        var oSheetItems = oSheet;
        if (oSheetItems != null)
        {
            oSheetItems.Name = "sheatName";
            int i = 1;

            foreach (var item in list)
            {
                //insert your object
                oSheetItems.Cells[i, 1] = item;
                oSheetItems.Cells[i, 2] = item;
                i++;
            }
        }

        fileName = Path.GetDirectoryName(Assembly.GetExecutingAssembly().Location)
                   + "\\ExcelName.xlsx";
        oWB.SaveAs(fileName, Excel.XlFileFormat.xlOpenXMLWorkbook,
            missing, missing, missing, missing,
            Excel.XlSaveAsAccessMode.xlNoChange,
            missing, missing, missing, missing, missing);
        oWB.Close(missing, missing, missing);
        oXL.UserControl = true;
        oXL.Quit();

if need more sheat: inter all code in loop an for every sheat use this code and change sheat with:如果需要更多的外壳:在循环中的所有代码中,对于每个外壳都使用此代码并使用以下代码更改外壳:

 Excel.Worksheet oSheet2 = oWB.Sheets.Add(missing, missing, 1, missing);
                oSheetItems = oSheet2;

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

相关问题 如何使用 C# 中的 NPOI 从现有 excel 文件中的列表中写入元素? - How to write element from a list in a existing excel file using NPOI in C#? 使用C#从excel写入文本文件 - Write text file from excel using C# 使用C#将数据从Excel工作表写入文本文件 - Write the data from an Excel sheet to the text file using C# 1)如何将Excel写入memorystream…2)如何使用Micosoft.Office.Interop.Excel和c#从浏览器下载Excel文件 - 1) how to write excel to memorystream…2) how to download excel file from browser…using Micosoft.Office.Interop.Excel and c# 使用C#将广告信息提取到Excel中 - Pulling AD info into Excel using C# 使用CsvHelper以动态方式从excel中写入csv文件 - Write csv file using CsvHelper, from excel in a dynamic way c# 如何使用c#从XML文件读取特定数据并将其写入到现有Excel工作表 - How to Read a particular Data from XML file and Write it to an Existing Excel Sheet using c# C# 使用 Interop 写入打开的 Excel 文件 - C# Write to an open Excel file using Interop 如何使用C#在特定单元格的Excel文件中写入数据 - How to write data in an excel file at particular cell using c# 如何使用C#打开带有写保护的excel文件 - How to open an excel file with write protection using C#
 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM