DataGrid到Excel?

我有一个在WPF中创建的程序。 它显示一个DataGrid其中包含来自MySQL数据库的数据。 我想要做的是允许用户将DataGrid的内容导出到Excel文件。 这可能与WPF有关吗?

当我使用此处显示的方法时: https : //www.outcoldman.ru/en/blog/show/201

导入到xls文件的唯一行是标题。

我也在寻找一些simillar来帮助将datagrid中的数据导出到excel中,但是没有找到任何有效的东西。 我刚刚将DataGrid的内容转换为字符串的2D数组,并使用interop dll将其导出。

代码看起来像这样:

  Excel.Application xlApp; Excel.Workbook xlWorkBook; Excel.Worksheet xlWorkSheet; object misValue = System.Reflection.Missing.Value; Excel.Range rangeToHoldHyperlink; Excel.Range CellInstance; xlApp = new Excel.Application(); xlWorkBook = xlApp.Workbooks.Add(misValue); xlWorkSheet = (Excel.Worksheet)xlWorkBook.Worksheets.get_Item(1); xlApp.DisplayAlerts = false; //Dummy initialisation to prevent errors. rangeToHoldHyperlink = xlWorkSheet.get_Range("A1", Type.Missing); CellInstance = xlWorkSheet.get_Range("A1", Type.Missing); for (int i = 0; i < NumberOfCols; i++) { for (int j = 0; j <= NumberOfRows; j++) { xlWorkSheet.Cells[j + 1, i + 1] = DataToWrite[j][i]; } } 

如果您正在寻找一些格式化,那么它们也受到支持。 我想添加一个超链接,以下代码执行此操作:

  CellInstance = xlWorkSheet.Cells[j + 1, i + 1]; xlWorkSheet.Hyperlinks.Add( CellInstance, DataToWrite[j][i], Type.Missing, "Hover Text Comes Here", "Text to be displayed"); 

如果您希望第一行是标题,可以按如下方式突出显示它们:

 Excel.Range Range1 = xlWorkSheet.get_Range("A1"); Range1.EntireRow.Font.Color = System.Drawing.ColorTranslator.ToOle(System.Drawing.Color.Black); Range1.EntireRow.Interior.Color = System.Drawing.ColorTranslator.ToOle(System.Drawing.Color.LightSkyBlue); Range1.EntireRow.Font.Size = 14; Range1.EntireRow.AutoFit(); 

最后将excel保存在所需的路径中:

 xlWorkBook.SaveAs(@FilePath, Excel.XlFileFormat.xlWorkbookNormal, misValue, misValue, misValue, misValue, Excel.XlSaveAsAccessMode.xlExclusive, misValue, misValue, misValue, misValue, misValue); xlWorkBook.Close(); 

对互操作的引用添加如下:

 Right Click on the Project name -> Click "Add reference" -> Goto "COM" tab -> Search for "Microsoft Excel Object Library" click "OK" to add the reference. 

您必须使用以下命名空间:

 using Excel = Microsoft.Office.Interop.Excel; using System.Runtime.InteropServices; 

您还可以将DataGrid内容导出为CSV文件。

我不知道你是否正在使用数据绑定,在这里我假设你这样做。

 var items = LoadItemsFromUnderlyingDataStore(); itemsDataGrid.ItemsSource = items; private void ItemsDataGridExportButton_Click(object sender, EventArgs e) { var filename = AutoGenerateDateTimedFileName(); using (var csv = new FileStream(filename)) { // if you want any column header in your Excel file, uncomment line below. //csv.WriteLine("Column1,Column2,Column3,Column4"); items.ForEach(item => csv.WriteLine("{0},{1},{2},{3}" , item.PropertyFromFirstColumn , item.PropertyFromSecondColumn , item.PropertyFromThirdColumn , item.PropertyFromFourthColumn); try { csv.Flush(); } catch(IOException ex) { // Handle error (log, whatever...) throw; // If you need to let the exception bubble up... } } } private string AutoGenerateDateTimedFileName() { return string.Format("DataGridExport_{0}_{1}.csv" , DataTime.Today.ToShortDateString() , DateTime.Now.ToLongTimeString()); } 

总之,此代码示例应该使用CSV文件,然后您可以使用Excel打开它。 您甚至可以在创建文件时启动Excel。

 private void ItemsDataGridExportButton_Click(object sender, EventArgs e) { // here's the upper code sample, and add the following: Process.Start(filename) } 

现在,使用Excel Interop。

 object[,] values = BuildTwoDimensionalMatrixFromDataGridContent(); Worksheet.Cells.Value(Microsoft.Office.Interop.Excel.XlRangeValueDataType.xlRangeValueDefault) = values; 

这可能是在Excel文件中设置值的最快方法,并且没有要解决的迭代。

使用CSV文件的第一个提议的解决方案可能是最容易理解和使用的。

放弃

这段代码是从我的头脑中创建的,因此尚未经过测试。 此代码可能需要进行一些更改才能正常使用程序的上下文。 此外,可能需要在此处显示的代码与您将能够与WPF一起使用的代码之间进行细微的差异分析。

最好的方法可能是为自己编写一个类库,该类库将与您的解决方案一起部署,该解决方案将使用简单的C#编写,以便您可以使用简单的Interop指令。

此链接可能对您有用 –

从Silverlight / WPF DataGrid将数据导出到Excel

示例代码从C:\ Windows \ WinSxS检索所有目录的列表,将其绑定到DataGrid并将DataGrid导出到Excel。 这里的核心是要知道将数据导出到Excel的最快方法是将数组分配给工作表。 但问题是我们无法直接从DataGrid获取此数组。 因此,我们首先需要填写它。 使用一点reflection,我们可以获取属性值并填充数组。 导出数据完全是一行。 我的计算机上的WinSxS文件夹包含14880个目录。 代码运行大约3秒钟(填充DataGrid +导出)。

  using Excel = Microsoft.Office.Interop.Excel; private void ExportDataGrid() { // Fetch directories var dirInfo = new DirectoryInfo(@"C:\Windows\WinSxS\"); var items = dirInfo.EnumerateDirectories(); dataGrid.ItemsSource = items; var source = dataGrid.ItemsSource; // Create Excel app var excel = new Excel.Application { Visible = true }; excel.ScreenUpdating = false; //Some speed-up var book = excel.Workbooks.Add(); var sheet = (Excel.Worksheet)book.Sheets[1]; int row = -1; //The row in array Type type = null; // Create array to hold data int rows = items.Count(), cols = dataGrid.Columns.Count; var arr = new object[rows, cols]; foreach (DirectoryInfo dir_info in dataGrid.ItemsSource) { ++row; // You can also use GetType().GetTypeInfo() as of .NET 4.5+. // The return type will be TypeInfo. type = dir_info.GetType(); for (int col = 0; col < cols; ++col) { var column_name = (string)dataGrid.Columns[col].Header; var value = type.GetProperty(column_name).GetValue(dir_info); arr.SetValue(value, row, col); } } // Create header for (int col = 0; c < cols; ++c) { sheet.Cells[1, col + 1].Value = dataGrid.Columns[col].Header; } // Dump array - the fastest way sheet.Range["A2"].Resize[rows, cols].Value = arr; // Restore screen updating - otherwise Excel will not response to actions excel.ScreenUpdating = true; }