[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();
    }
  }

 


免責聲明!

本站轉載的文章為個人學習借鑒使用,本站對版權不負任何法律責任。如果侵犯了您的隱私權益,請聯系本站郵箱yoyou2525@163.com刪除。



 
粵ICP備18138465號   © 2018-2025 CODEPRJ.COM