在完成将DataGrid的内容导出到Excel的时候,参考了一个印度小伙的文章http://www.codeproject.com/Articles/120480/Export-to-Excel-Functionality-in-WPF-DataGrid,很清晰,结合着自己的实际项目写了这篇文章,分享给大家。
这里不多讲,直接拖控件就行。
这里查询结果返回的是泛型,
在XAML文件中需要绑定数据:
<DataGrid x:Name="dgtOnlineRecord" Grid.ColumnSpan="4" Grid.Column="1" HorizontalAlignment="Left" Height="432.842" Grid.Row="4" VerticalAlignment="Top" Width="703.722"
ItemsSource="{Binding}" AutoGenerateColumns="False">
<DataGrid.Columns>
<DataGridTextColumn Header="卡号" Binding="{Binding cardID}"/>
<DataGridTextColumn Header="上机时间" Binding="{Binding onLineDateTime}"/>
<DataGridTextColumn Header="下机时间" Binding="{Binding offLineDateTime}"/>
<DataGridTextColumn Header="消费金额" Binding="{Binding costCash}"/>
<DataGridTextColumn Header="上机机器" Binding="{Binding onLineComputer}"/>
DataGrid.Columns>
DataGrid>
后台代码:
JFFacade.CardManagerFacade cardmanagerfacade = new JFFacade.CardManagerFacade();
//实例化外观层的CardManagerFacade类
dgtOnlineRecord.ItemsSource = cardmanagerfacade.QueryStuOnlineRecord(combinedquery);
//使用QueryStuOnlineRecord(查询学生上机记录)方法,并将返回值赋给datagrid的ItemSource
效果如下所示:
这里把它封装成了一个类,方便复用,放到了Common层
#region ExportToExcel 导出为Excel
///
/// 导出Excel类
///
///
///
public class ExportToExcel
where T : class
where U : List
{
public List DataToPrint;
// Excel 对象实例.
private Excel.Application _excelApp = null;
private Excel.Workbooks _books = null;
private Excel._Workbook _book = null;
private Excel.Sheets _sheets = null;
private Excel._Worksheet _sheet = null;
private Excel.Range _range = null;
private Excel.Font _font = null;
// 可选 参数
private object _optionalValue = Missing.Value;
///
/// 生成报表,和其他功能
///
///
public int GenerateReport()
{
int result = 1;
try
{
if (DataToPrint != null)
{
if (DataToPrint.Count != 0)
{
CreateExcelRef();
FillSheet();
OpenReport();
}
}
}
catch (Exception e)
{
result = 0;
//("Excel导出失敗!\n", e.Message);
}
finally
{
ReleaseObject(_sheet);
ReleaseObject(_sheets);
ReleaseObject(_book);
ReleaseObject(_books);
ReleaseObject(_excelApp);
}
return result;
}
///
/// 展示 Excel 程序
///
private void OpenReport()
{
_excelApp.Visible = true;
}
///
/// 填充 Excel sheet
///
private void FillSheet()
{
object[] header = CreateHeader();
WriteData(header);
}
///
/// 将数据写入 Excel sheet
///
///
private void WriteData(object[] header)
{
object[,] objData = new object[DataToPrint.Count, header.Length];
for (int j = 0; j < DataToPrint.Count; j++)
{
var item = DataToPrint[j];
for (int i = 0; i < header.Length; i++)
{
var y = typeof(T).InvokeMember(header[i].ToString(),
BindingFlags.GetProperty, null, item, null);
objData[j, i] = (y == null) ? "" : y.ToString();
}
}
AddExcelRows("A2", DataToPrint.Count, header.Length, objData);
AutoFitColumns("A1", DataToPrint.Count + 1, header.Length);
}
///
/// 根据数据拟合 列
///
///
///
///
private void AutoFitColumns(string startRange, int rowCount, int colCount)
{
_range = _sheet.get_Range(startRange, _optionalValue);
_range = _range.get_Resize(rowCount, colCount);
_range.Columns.AutoFit();
}
///
/// 根据属性名创建列标题
///
///
private object[] CreateHeader()
{
PropertyInfo[] headerInfo = typeof(T).GetProperties();
// 为 标头 创建 Array
// 开始从 A1 处添加
List<object> objHeaders = new List<object>();
for (int n = 0; n < headerInfo.Length; n++)
{
objHeaders.Add(headerInfo[n].Name);
}
var headerToAdd = objHeaders.ToArray();
AddExcelRows("A1", 1, headerToAdd.Length, headerToAdd);
SetHeaderStyle();
return headerToAdd;
}
///
/// 列标题设置为加粗字体
///
private void SetHeaderStyle()
{
_font = _range.Font;
_font.Bold = true;
}
///
/// 添加行
///
///
///
///
///
private void AddExcelRows(string startRange, int rowCount,
int colCount, object values)
{
_range = _sheet.get_Range(startRange, _optionalValue);
_range = _range.get_Resize(rowCount, colCount);
_range.set_Value(_optionalValue, values);
}
///
/// 创建 Excel 传递的参数实例
///
private void CreateExcelRef()
{
_excelApp = new Excel.Application();
_books = (Excel.Workbooks)_excelApp.Workbooks;
_book = (Excel._Workbook)(_books.Add(_optionalValue));
_sheets = (Excel.Sheets)_book.Worksheets;
_sheet = (Excel._Worksheet)(_sheets.get_Item(1));
}
///
/// 释放未使用的对象
///
///
private void ReleaseObject(object obj)
{
try
{
System.Runtime.InteropServices.Marshal.ReleaseComObject(obj);
obj = null;
}
catch (Exception ex)
{
obj = null;
//MessageBox.Show(ex.Message.ToString());
}
finally
{
GC.Collect();
}
}
}
#endregion
///
/// 导出为Excel
///
///
///
private void btnExport_Click(object sender, RoutedEventArgs e)
{
Common.ExportToExcel> exporttoexcel =
new Common.ExportToExcel>();
//实例化exporttoexcel对象
exporttoexcel.DataToPrint = (List)dgtOnlineRecord.ItemsSource;
exporttoexcel.GenerateReport();
}
导出的Excel:
可能出现的问题及解决方案
需要添加引用:
使用命名空间:
using System.Reflection;
using Excel = Microsoft.Office.Interop.Excel;