【问题标题】:DataTable to excel conversion数据表到excel的转换
【发布时间】:2013-06-16 08:02:46
【问题描述】:

我有一个填充数据表的数据网格,我想通过单击按钮将数据表导出到 excel。我正在为这个应用程序使用 MVVM。那么在我看来可以实现导出功能吗?

其次,当我使用 xaml 和桌面应用程序时,我如何捕获网格及其详细信息。

谁能给我一些建议?我是新手。

谢谢, 萨加尔

【问题讨论】:

  • ClosedXML 视为第三方库,以帮助清理一些必要的代码
  • @KyleMit ClosedXML 是基于 ASP.net 的,我需要在使用 xaml 控件和 mvvm 架构的应用程序中使用此功能。

标签: excel xaml data-binding mvvm datagrid


【解决方案1】:

这就是我所做的,它帮助了我:

private readonly ICommand m_ExportButtonClick;
    private string ExcelFilePath = "";

    public ICommand ExportButtonClick { get { return m_ExportButtonClick; } }

    private void OnRunExport()
    {
        try
        {
            if (queryDatatable == null || queryDatatable.Columns.Count == 0)
                throw new Exception("ExportToExcel: Null or empty input table!\n");

            // load excel, and create a new workbook
            Excell.Application excelApp = new Excell.Application();
            excelApp.Workbooks.Add();

            // single worksheet
            Excell._Worksheet workSheet = excelApp.ActiveSheet;

            // column headings
            for (int i = 0; i < queryDatatable.Columns.Count; i++)
            {
                workSheet.Cells[1, (i + 1)] = queryDatatable.Columns[i].ColumnName;
            }

            // rows
            for (int i = 0; i < queryDatatable.Rows.Count; i++)
            {
                // to do: format datetime values before printing
                for (int j = 0; j < queryDatatable.Columns.Count; j++)
                {
                    workSheet.Cells[(i + 2), (j + 1)] = queryDatatable.Rows[i][j];
                }
            }

            // check fielpath
            if (ExcelFilePath != null && ExcelFilePath != "")
            {
                try
                {                        
                    workSheet.SaveAs(ExcelFilePath);
                    excelApp.Quit();
                    MessageBox.Show("Excel file saved!");
                }
                catch (Exception ex)
                {
                    throw new Exception("ExportToExcel: Excel file could not be saved! Check filepath.\n"
                        + ex.Message);
                }
            }
            else    // no filepath is given, the file opens up and the user can save it accordingly.
            {
                excelApp.Visible = true;
            }
        }
        catch (Exception ex)
        {
            MessageBox.Show("There is no data to export. Please check your query/ Contact administrator." + ex.Message);
        }
    }      
    #endregion

【讨论】:

    【解决方案2】:

    试着用谷歌搜索一下。这是一个非常常见的问题,并且已经被问了很多。这是SO question的一个很好的答案

    public static void ExportToExcel<T>(IEnumerable<T> exportData)
    {
        Excel.ApplicationClass excel = new Excel.ApplicationClass();
        Excel.Workbook workbook = excel.Application.Workbooks.Add(true);
        PropertyInfo[] pInfos = typeof(T).GetProperties();
        if (pInfos != null && pInfos.Count() > 0)
        {
            int iCol = 0;
            int iRow = 0;
            foreach (PropertyInfo eachPInfo in pInfos.Where(W => W.CanRead == true))
            {
                // Add column headings...
                iCol++;
                excel.Cells[1, iCol] = eachPInfo.Name;
            }
            foreach (T item in exportData)
            {
                iRow++;
                // add each row's cell data...
                iCol = 0;
                foreach (PropertyInfo eachPInfo in pInfos.Where(W => W.CanRead == true))
                {
                    iCol++;
                    excel.Cells[iRow + 1, iCol] = eachPInfo.GetValue(item, null);
                }
    
            }
            // Global missing reference for objects we are not defining...
            object missing = System.Reflection.Missing.Value;
            // If wanting to Save the workbook...   
            string filePath = System.IO.Path.GetTempPath() + DateTime.Now.Ticks.ToString() + ".xlsm";
            workbook.SaveAs(filePath, Excel.XlFileFormat.xlOpenXMLWorkbookMacroEnabled, missing, missing, false, false, Excel.XlSaveAsAccessMode.xlNoChange, missing, missing, missing, missing, missing);
            // If wanting to make Excel visible and activate the worksheet...
            excel.Visible = true;
            Excel.Worksheet worksheet = (Excel.Worksheet)excel.ActiveSheet;
            excel.Rows.EntireRow.AutoFit();
            excel.Columns.EntireColumn.AutoFit();
            ((Excel._Worksheet)worksheet).Activate();
        }
    }
    

    【讨论】:

    • 谢谢,我使用的是 .Net framework 4.0,我认为 ApplicationClass 不受 4.0 支持。当我尝试重构时,它不允许我这样做。
    【解决方案3】:

    这是一种将任何DataTable输出到csv(excel可以打开)的扩展方法

    Imports System.Text
    Imports System.IO
    Imports System.Runtime.CompilerServices
    
    Module ExtensionMethods
    
        <Extension()> _
        Public Sub OutputAsCSV(ByVal dt As DataTable, ByVal filePath As String)
            Dim sb As New StringBuilder()
    
                    'write column names to string builder
            Dim columnNames As String() = (From col As DataColumn In dt.Columns Select col.ColumnName).ToArray
            sb.AppendLine(String.Join(",", columnNames))
    
                    'write cell value in each row to string builder
            For Each row As DataRow In dt.Rows
                Dim fields As String() = (From cell In row.ItemArray Select CStr(cell)).ToArray
                sb.AppendLine(String.Join(",", fields))
            Next
    
                    'write string builder to file
            File.WriteAllText(filePath, sb.ToString())
        End Sub
    
    End Module
    

    【讨论】:

      猜你喜欢
      • 1970-01-01
      • 1970-01-01
      • 2014-06-09
      • 1970-01-01
      • 2011-03-18
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      相关资源
      最近更新 更多