使用c#读/写一个简单的excel文件

本文关键字:一个 简单 文件 excel 使用 | 更新日期: 2023-09-27 18:22:32

我正试图找到一种用c#编写excel文件的简单方法,但我在上找到的一切都感谢您的帮助。

使用c#读/写一个简单的excel文件

有两个选项

第一个是使用互操作程序集。这里有一些示例代码的链接,介绍如何使用C#将数据写入Excel

第二种选择是使用OLEDB。这里有一些关于堆栈溢出的信息

如上所述使用epplus,它使它变得非常简单。这是我今天用它创建的电子表格的代码。

            using (ExcelPackage pck = new ExcelPackage())
        {
            //Give the worksheet a name
            ExcelWorksheet ws = pck.Workbook.Worksheets.Add("Inventory as of " + DateTime.Now.ToString("MM/dd/yyyy"));
            //dt is a datable that i am turning into an excel document
            ws.Cells["A1"].LoadFromDataTable(dt, true);
            //Format the header columns(Color,Pattern,etc.)
            using (ExcelRange rng = ws.Cells["A1:AA1"])
            {
                rng.Style.Font.Bold = true;
                rng.Style.Fill.PatternType = ExcelFillStyle.Solid;             //Set Pattern for the background to Solid
                rng.Style.Fill.BackgroundColor.SetColor(Color.FromArgb(79, 129, 189));  //Set color to dark blue
                rng.Style.Font.Color.SetColor(Color.White);
            }
            //End Format the header columns
            //Give the file details(ie. filename, etc.)
            Response.ContentType = "application/vnd.openxmlformats-officedocument.spreadsheetml.sheet";
            Response.AddHeader("content-disposition", "attachment;filename=Inventory Report " + DateTime.Now.ToString("MM/dd/yyyy") + ".xlsx");
            //Write the file
            Response.BinaryWrite(pck.GetAsByteArray());
            Response.End();
            pck.Save();
        }

您需要的是epplus,这将帮助您创建2007+excel文件

与2003和不兼容

根据您想要编写的excel文件的版本,没有真正简单的方法。如果你想使用xls,除了使用Excel互操作之外,你没有太多选择,因为Excel互操作也依赖于安装Excel
新版本提供了更多的选项,因为它只是后台的XML。您可以自己选择如何创建它,可以自己创建,也可以选择一些库或再次创建Interop
如果你只想显示一个没有任何样式的表格,有一种(afair)写csv文件的方法,excel可以很好地打开它(取决于你想在其中使用的数据类型)。