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

      

  • 相关阅读:
    1004 Counting Leaves
    1003 Emergency (25分)
    1002 A+B for Polynomials (25分)
    1001 A+B Format
    Weekly Contest 139
    491. Increasing Subsequences
    488. Zuma Game
    servlet总结
    firefox插件Firebug的使用教程
    KMP---POJ 3461 Oulipo
  • 原文地址:https://www.cnblogs.com/jack-jun/p/12612076.html
Copyright © 2011-2022 走看看