C#DataTable匯出Excel

來源:互聯網
上載者:User

標籤:c# datatable excel

先將資料庫中的資料讀取到DataTable中,然後調用下面的代碼,"cells.Add(1, 1, "表頭1");"這段代碼的意思是在Excel中添加一行表頭,比如“姓名”,“性別”,“聯絡電話”等,需要幾列就對應的添加幾列。“cells.Add(2 + row, 1, dt.Rows[row]["對應表頭1的欄位"]);”這段代碼的意思是擷取對應表頭的資料,比如表頭1如果為“姓名”,這裡"對應表頭1的欄位"就改成欄位"Name"。

DataTable dt = GetDataTable();                    if (dt == null)                        return;                    try                    {                        XlsDocument xls = new XlsDocument();                        string fileName = Guid.NewGuid().ToString() + ".xls";                        xls.FileName = fileName;                        string sheetName = "Sheet1";                        Worksheet sheet = xls.Workbook.Worksheets.Add(sheetName);                        Cells cells = sheet.Cells;                        cells.Add(1, 1, "表頭1");                        cells.Add(1, 2, "表頭2");                        cells.Add(1, 3, "表頭3");                        cells.Add(1, 4, "表頭4");                        cells.Add(1, 5, "表頭5");                        cells.Add(1, 6, "表頭6");                        cells.Add(1, 7, "表頭7");                        cells.Add(1, 8, "表頭8");                        for (int row = 0; row < dt.Rows.Count; row++)                        {                            cells.Add(2 + row, 1, dt.Rows[row]["對應表頭1的欄位"]);                            cells.Add(2 + row, 2, dt.Rows[row]["對應表頭2的欄位"]);                            cells.Add(2 + row, 3, dt.Rows[row]["對應表頭3的欄位"]);                            cells.Add(2 + row, 4, dt.Rows[row]["對應表頭4的欄位"]);                            cells.Add(2 + row, 5, dt.Rows[row]["對應表頭5的欄位"]);                            cells.Add(2 + row, 6, dt.Rows[row]["對應表頭6的欄位"]);                            cells.Add(2 + row, 7, dt.Rows[row]["對應表頭7的欄位"]);                            cells.Add(2 + row, 8, dt.Rows[row]["對應表頭8的欄位"]);                        }                        string filePath = Server.MapPath("~/tmp/");                        xls.Save(filePath);                        xls = null;                    }                    catch (Exception)                    {                        throw;                    }


C#DataTable匯出Excel

相關文章

聯繫我們

該頁面正文內容均來源於網絡整理,並不代表阿里雲官方的觀點,該頁面所提到的產品和服務也與阿里云無關,如果該頁面內容對您造成了困擾,歡迎寫郵件給我們,收到郵件我們將在5個工作日內處理。

如果您發現本社區中有涉嫌抄襲的內容,歡迎發送郵件至: info-contact@alibabacloud.com 進行舉報並提供相關證據,工作人員會在 5 個工作天內聯絡您,一經查實,本站將立刻刪除涉嫌侵權內容。

A Free Trial That Lets You Build Big!

Start building with 50+ products and up to 12 months usage for Elastic Compute Service

  • Sales Support

    1 on 1 presale consultation

  • After-Sales Support

    24/7 Technical Support 6 Free Tickets per Quarter Faster Response

  • Alibaba Cloud offers highly flexible support services tailored to meet your exact needs.