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

      

  • 相关阅读:
    判断分流使用
    Mac系统如何显示隐藏文件?
    Brew安装的软件查询安装位置
    JetBrains 产品线破解方法
    Linux查看与挂载新磁盘
    对BRD、MRD、PRD、FSD四类产品文档的理解
    网站收藏
    收藏
    官方文档
    java 的访问权限控制
  • 原文地址:https://www.cnblogs.com/jack-jun/p/12612076.html
Copyright © 2020-2023  润新知