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

时间:2013-07-15 23:17:59

标签: c# excel

我正在尝试找一种在c#中编写excel文件的简单方法,但我发现的所有内容都要感谢您的帮助。

4 个答案:

答案 0 :(得分:1)

您有两种选择

第一个是在这里使用Interop程序集链接到一些示例代码如何执行Write Data to Excel using C#

第二种选择是使用OLEDB。有关here

的Stack Overflow的一些信息

答案 1 :(得分:1)

如上所述使用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();

        }

答案 2 :(得分:0)

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

与2003年及

不兼容

答案 3 :(得分:0)

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

相关问题