[C#]创建表格(.xlsx)的典型方法

Time:2017-10-11   10:12:13

利用EPPlus(4.1):

下载引用地址:http://epplus.codeplex.com/

  --EPPlus is a .net library that reads and writes Excel 2007/2010 files using the Open Office Xml format (xlsx). 

  --EPPlus是一个.net库,它使用Open Office Xml格式(xlsx)读取和写入Excel 200/2010文件。

注意:不要忘记引用EPPlus

代码:(根据不同需求进行改动)

  public static void createExcel()
  {
    //创建表格的具体路径
    var file = @"C:...Sample.xlsx";
    //如果存在此表格,进行删除操作
    if (File.Exists(file)) 
    {
      File.Delete(file);
    }
    using (var excel = new ExcelPackage(new FileInfo(file)))
    {

      //创建一个工作表
      var ws = excel.Workbook.Worksheets.Add("Sheet1");

      //设置表格中的第一行的内容
      ws.Cells[1, 1].Value = "Date";
      ws.Cells[1, 2].Value = "Price";
      ws.Cells[1, 3].Value = "Volume";

      //设置表格中单元格的内容(从第二行开始)
      for (int i = 0; i < 10; i++)
      {
        ws.Cells[i + 2, 1].Value = DateTime.Today.AddDays(i);
        ws.Cells[i + 2, 2].Value = random.NextDouble() * 1e3;
        ws.Cells[i + 2, 3].Value = random.Next() / 1e3;
      }

      //设置表格中单元格的内容的格式
      ws.Cells[2, 1, 11, 1].Style.Numberformat.Format = "yyyy.MM.dd";
      ws.Cells[2, 2, 11, 2].Style.Numberformat.Format = "#,##0.00";
      ws.Cells[2, 3, 11, 3].Style.Numberformat.Format = "#,##0";

      //自动调整每一列的长宽高
      ws.Column(1).AutoFit();
      ws.Column(2).AutoFit();
      ws.Column(3).AutoFit();

      //保存表格信息
      excel.Save();
    }
  }
原文地址:https://www.cnblogs.com/ttkl/p/7649202.html