DataTable可以实现卓越的转换

时间:2013-06-19 17:00:40

标签: excel xaml data-binding mvvm datagrid

我有一个填充数据表的数据网格,我想在点击按钮时将DataTable导出为ex​​cel。我在这个应用程序中使用MVVM。那么在我的视图中实现导出功能是否可以?

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

任何人都可以向我提出一些建议吗?我是新手。

谢谢, Sagar的

3 个答案:

答案 0 :(得分: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

答案 1 :(得分:0)

这是一个输出到任何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

答案 2 :(得分:0)

尝试谷歌搜索一下。这是一个非常普遍的问题,并且已经被问过很多。这是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();
    }
}