C#将数据表导出到具有三个工作表的.xlsx文件中

问题描述 投票:0回答:1

我在数据表中有SQL数据行,目前具有以下代码,这些代码输出到.csv文件中。我需要创建一个带有三个标签的Excel文件。第一个选项卡必须是带有三个标题的空白工作表。中间选项卡必须是数据表的输出。最终选项卡需要是另一个包含三个标题的空白工作表。如何自动创建具有三个选项卡的excel工作簿,中间的选项卡填充数据表输出。

 StringBuilder sb = new StringBuilder();

            IEnumerable<string> columnNames = dt.Columns.Cast<DataColumn>().
                                              Select(column => column.ColumnName);
            sb.AppendLine(string.Join(",", columnNames));

            foreach (DataRow row in dt.Rows)
            {
                IEnumerable<string> fields = row.ItemArray.Select(field => field.ToString());
                sb.AppendLine(string.Join(",", fields));
            }

            // Specify a "currently active folder"
            string activeDir = @"C:\Users\Roger\Documents\Price_Files";

            string foldername = "PriceFile_" + DateTime.Today.ToString("yyyyMMdd");

            //Create a new subfolder under the current active folder
            string newPath = System.IO.Path.Combine(activeDir, foldername);

            // Create the subfolder
            System.IO.Directory.CreateDirectory(newPath);

            string filename = newPath + "\\" + "PriceFile_" + DateTime.Today.ToString("yyyyMMdd") + "_Retail_" + jurisdiction;

            File.WriteAllText(filename + ".csv", sb.ToString());
c# excel
1个回答
0
投票

使用EPPlus库

                 using (ExcelPackage excel = new ExcelPackage())
                {
                    excel.Workbook.Worksheets.Add("Tab1"); // Create first tab
                    excel.Workbook.Worksheets.Add("Tab2");//Create second tab
                    excel.Workbook.Worksheets.Add("Tab3");//Create third tab
                    var excelWorksheet = excel.Workbook.Worksheets["Tab2"];
                    //Set value for 1 cell in 1 row in Tab2
                    excelWorksheet.Cells[1, 1].Value = "Some text";
                    //Simple aligment and fond for this cell
                    excelWorksheet.Cells[1, 1].Style.HorizontalAlignment = OfficeOpenXml.Style.ExcelHorizontalAlignment.Center;
                    excelWorksheet.Cells[1, 1].Style.Font.Bold = true;
                    //adding data to cells from dataTable in the loop
                    foreach (DataRow row in dataTable)
                    {
                        excelWorksheet.Cells[position, 1].Value = row["*column_name*"].ToString();
                    }


                }

或者,也可以通过调用LoadFromDataTable方法加载所有dataTable,而不是循环设置数据

excelWorksheet.Cells[1, 1].LoadFromDataTable(dataTable, true);

最后调用excel.GetAsByteArray()以将文件作为字节数组或调用excel.SaveAs(...)从心理上将其保存在硬盘上

© www.soinside.com 2019 - 2024. All rights reserved.