zoukankan      html  css  js  c++  java
  • Datatable转Excel

    public static void ExportToExcel( DataTable tbl, string excelFilePath = null)
    {
    try
    {
    if (tbl == null || tbl.Columns.Count == 0)
    throw new Exception("ExportToExcel: Null or empty input table!
    ");
    
    // load excel, and create a new workbook
    var excelApp = new Excel.Application();
    excelApp.Workbooks.Add();
    
    // single worksheet
    Excel._Worksheet workSheet = excelApp.ActiveSheet;
    
    // column headings
    for (var i = 0; i < tbl.Columns.Count; i++)
    {
    workSheet.Cells[1, i + 1] = tbl.Columns[i].ColumnName;
    }
    
    // rows
    for (var i = 0; i < tbl.Rows.Count; i++)
    {
    // to do: format datetime values before printing
    for (var j = 0; j < tbl.Columns.Count; j++)
    {
    workSheet.Cells[i + 2, j + 1] = tbl.Rows[i][j];
    }
    }
    
    // check file path
    if (!string.IsNullOrEmpty(excelFilePath))
    {
    try
    {
    workSheet.SaveAs(excelFilePath);
    excelApp.Quit();
    Console.WriteLine("Excel file saved!");
    }
    catch (Exception ex)
    {
    throw new Exception("ExportToExcel: Excel file could not be saved! Check filepath.
    "
    + ex.Message);
    }
    }
    else
    { // no file path is given
    excelApp.Visible = true;
    }
    }
    catch (Exception ex)
    {
    throw new Exception("ExportToExcel: 
    " + ex.Message);
    }
    }
    

      

  • 相关阅读:
    Java1:Chapter2
    Java1:Chapter1
    Java1:Chapter11
    Java1:Chapter8
    Java1:Chapter6
    Android day 03
    Android day02
    Android day01
    二进制文件的读写
    字符流
  • 原文地址:https://www.cnblogs.com/jack-jun/p/12612076.html
Copyright © 2011-2022 走看看