WPF DataGrid到Excel [英] WPF DataGrid to Excel

查看:71
本文介绍了WPF DataGrid到Excel的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

Hi


如何将数据从WPF(基于窗口)Datagrid以相同的格式导出到Excel,因为我在Datagrid中使用了多个标头。请帮帮我。



Thnx

解决方案

dgDisplay是一个DataGrid Name.Hope下面的代码将会解决你的问题。



  private   void  ExportToExcelAndCsv()
{
dgDisplay.SelectAllCells();
dgDisplay.ClipboardCopyMode = DataGridClipboardCopyMode.IncludeHeader;
ApplicationCommands.Copy.Execute( null ,dgDisplay);
String resultat =( string )Clipboard.GetData(DataFormats.CommaSeparatedValue);
String result =( string )Clipboard.GetData(DataFormats.Text);
dgDisplay.UnselectAllCells();
System.IO.StreamWriter file1 = new System.IO.StreamWriter( @ C:\Users\test.xls);
file1.WriteLine(result.Replace(' ,'' '));
file1.Close();

MessageBox.Show( 将DataGrid数据导出到Excel文件created.xls);
}


这将是一个手动过程。我为导出Excel所做的示例:

  private   static   void  Excel( string  fileName,List< IDirectoryInventoryDataCollector> list)
{
尝试
{
var xlApp = new Excel.Application();
var xlWorkBook = xlApp.Workbooks.Add();
var xlWorkSheet =(Excel.Worksheet)xlWorkBook.Worksheets.get_Item( 1 );
ExcelTitleRow(list [ 0 ], 1 ,xlWorkSheet);

int row = 2 ;
foreach var item in list)
{
ExcelFillRow(item,row ++,xlWorkSheet);
}

for int i = 1 ; i < list [ 0 ]。MaxLevel - 1 ; i ++)
{
((Range)xlWorkSheet.Columns [i])。ColumnWidth = 2 ;
}
((范围)xlWorkSheet.Columns [list [ 0 ]。MaxLevel - 1 ]).ColumnWidth = 30 ;
((范围)xlWorkSheet.Rows [ 1 ])。WrapText = true ;
((范围)xlWorkSheet.Rows [ 1 ])。Horizo​​ntalAlignment = Horizo​​ntalAlignment.Center;
((范围)xlWorkSheet.Cells [ 1 1 ])。WrapText = ;

xlWorkBook.SaveAs(fileName);
xlWorkBook.Close();
xlApp.Quit();
}
catch (AccessViolationException)
{
System.Windows.Forms.MessageBox.Show(
遇到访问冲突。如果仅在计算机上安装了版本,则可能是Excel 2000的问题
访问冲突);
}
catch (例外)
{
System.Windows.Forms.MessageBox.Show( 未知错误
未知错误);
}
}

私有 静态 void ExcelFillRow(IDirectoryInventoryDataCollector item, int 行,Excel.Worksheet表格)
{
sheet .Cells [row,item.Level] = item.Name;
int column = item.MaxLevel;
foreach var property in item.GetProperties())
{
sheet.Cells [row,column ++] = property;
}
}

私有 静态 void ExcelTitleRow(IDirectoryInventoryDataCollector item, int 行,Excel.Worksheet表格)
{
sheet .Cells [row, 1 ] = 名称< /跨度>;
int column = item.MaxLevel;
foreach var property in item.GetPropertyNames())
{
sheet.Cells [row,column ++] = property;
}
}



您需要的命名空间是

 使用 Excel = Microsoft.Office.Interop.Excel; 
使用 Microsoft.Office.Interop.Excel;


检查这个WPF DataGrid到Excel的代码



dataGrid是DataGrid的名称。



 DataGrid dg = dataGrid; 
dg.SelectAllCells();
dg.ClipboardCopyMode = DataGridClipboardCopyMode.IncludeHeader;
ApplicationCommands.Copy.Execute(null,dg);
dg.UnselectAllCells();
String Clipboardresult =(string)Clipboard.GetData(DataFormats.CommaSeparatedValue);
StreamWriter swObj = new StreamWriter(exportToExcel.csv);
swObj.WriteLine(Clipboardresult);
swObj.Close();
Process.Start(exportToExcel.csv);





上面的代码不需要任何dll来创建excel文件。


Hi
How to Export Data from WPF(Window based) Datagrid to Excel in same format becasue i m using multiple header in Datagrid. please help me out.

Thnx

解决方案

dgDisplay is a DataGrid Name.Hope the below code will solve your problem.

private void ExportToExcelAndCsv()
       {
           dgDisplay.SelectAllCells();
           dgDisplay.ClipboardCopyMode = DataGridClipboardCopyMode.IncludeHeader;
           ApplicationCommands.Copy.Execute(null, dgDisplay);
           String resultat = (string)Clipboard.GetData(DataFormats.CommaSeparatedValue);
           String result = (string)Clipboard.GetData(DataFormats.Text);
           dgDisplay.UnselectAllCells();
           System.IO.StreamWriter file1 = new System.IO.StreamWriter(@"C:\Users\test.xls");
           file1.WriteLine(result.Replace(',', ' '));
           file1.Close();

           MessageBox.Show(" Exporting DataGrid data to Excel file created.xls");
       }


It is going to have to be a manual process. Sample of what I have done to export Excel:

private static void Excel(string fileName, List<IDirectoryInventoryDataCollector> list)
{
    try
    {
        var xlApp = new Excel.Application();
        var xlWorkBook = xlApp.Workbooks.Add();
        var xlWorkSheet = (Excel.Worksheet)xlWorkBook.Worksheets.get_Item(1);
        ExcelTitleRow(list[0], 1, xlWorkSheet);

        int row = 2;
        foreach (var item in list)
        {
            ExcelFillRow(item, row++, xlWorkSheet);
        }

        for (int i = 1; i < list[0].MaxLevel - 1; i++)
        {
            ((Range)xlWorkSheet.Columns[i]).ColumnWidth = 2;
        }
        ((Range)xlWorkSheet.Columns[list[0].MaxLevel - 1]).ColumnWidth = 30;
        ((Range)xlWorkSheet.Rows[1]).WrapText = true;
        ((Range)xlWorkSheet.Rows[1]).HorizontalAlignment = HorizontalAlignment.Center;
        ((Range)xlWorkSheet.Cells[1, 1]).WrapText = false;

        xlWorkBook.SaveAs(fileName);
        xlWorkBook.Close();
        xlApp.Quit();
    }
    catch (AccessViolationException)
    {
        System.Windows.Forms.MessageBox.Show(
             "Have encountered access violation. This could be issue with Excel 2000 if that is only version installed on computer",
             "Access Violation");
    }
    catch (Exception)
    {
        System.Windows.Forms.MessageBox.Show("Unknown error",
             "Unknown error");
    }
}

private static void ExcelFillRow(IDirectoryInventoryDataCollector item, int row, Excel.Worksheet sheet)
{
    sheet.Cells[row, item.Level] = item.Name;
    int column = item.MaxLevel;
    foreach (var property in item.GetProperties())
    {
        sheet.Cells[row, column++] = property;
    }
}

private static void ExcelTitleRow(IDirectoryInventoryDataCollector item, int row, Excel.Worksheet sheet)
{
    sheet.Cells[row, 1] = "Name";
    int column = item.MaxLevel;
    foreach (var property in item.GetPropertyNames())
    {
        sheet.Cells[row, column++] = property;
    }
}


The namespace you need are

using Excel = Microsoft.Office.Interop.Excel;
using Microsoft.Office.Interop.Excel;


Check this code for WPF DataGrid to Excel

dataGrid is name of DataGrid.

DataGrid dg = dataGrid;
dg.SelectAllCells();
dg.ClipboardCopyMode = DataGridClipboardCopyMode.IncludeHeader;
ApplicationCommands.Copy.Execute(null, dg);
dg.UnselectAllCells();
String Clipboardresult =(string)Clipboard.GetData(DataFormats.CommaSeparatedValue);
StreamWriter swObj = new StreamWriter("exportToExcel.csv");
swObj.WriteLine(Clipboardresult);
swObj.Close();
Process.Start("exportToExcel.csv");



Above code not required any dll to create the excel file.


这篇关于WPF DataGrid到Excel的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆