c# – 将DataGrid导出为CSV或Excel

c# – 将DataGrid导出为CSV或Excel,第1张

概述如何将我的DataGrid信息导出到.csv或excel文件中? 我正在使用Microsoft Visual Studio 2010与.NET Framework 4.0. 尝试下面的样本 private void btnexport_Click(object sender, RoutedEventArgs e){ ExportToExcel<Employee, Employees> s 如何将我的DataGrID信息导出到.csv或excel文件中?
我正在使用Microsoft Visual Studio 2010与.NET Framework 4.0.解决方法 尝试下面的样本

private voID btnexport_Click(object sender,RoutedEventArgs e){    ExportToExcel<Employee,Employees> s = new ExportToExcel<Employee,Employees>();    s.datatoprint = (Employees)dgEmployee.ItemsSource;    s.GenerateReport();}/// <summary>/// Class for generator of Excel file/// </summary>/// <typeparam name="T"></typeparam>/// <typeparam name="U"></typeparam>public class ExportToExcel<T,U>    where T : class    where U : List<T>{    public List<T> datatoprint;    // Excel object references.    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;    // Optional argument variable    private object _optionalValue = Missing.Value;    /// <summary>    /// Generate report and sub functions    /// </summary>    public voID GenerateReport()    {        try        {            if (datatoprint != null)            {                if (datatoprint.Count != 0)                {                    Mouse.SetCursor(Cursors.Wait);                    CreateExcelRef();                    FillSheet();                    OpenReport();                    Mouse.SetCursor(Cursors.Arrow);                }            }        }        catch (Exception e)        {            MessageBox.Show("Error while generating Excel report");        }        finally        {            ReleaSEObject(_sheet);            ReleaSEObject(_sheets);            ReleaSEObject(_book);            ReleaSEObject(_books);            ReleaSEObject(_excelApp);        }    }    /// <summary>    /// Make Microsoft Excel application visible    /// </summary>    private voID OpenReport()    {        _excelApp.Visible = true;    }    /// <summary>    /// Populate the Excel sheet    /// </summary>    private voID FillSheet()    {        object[] header = Createheader();        WriteData(header);    }    /// <summary>    /// Write data into the Excel sheet    /// </summary>    /// <param name="header"></param>    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);    }    /// <summary>    /// Method to make columns auto fit according to data    /// </summary>    /// <param name="startRange"></param>    /// <param name="rowCount"></param>    /// <param name="colCount"></param>    private voID autoFitColumns(string startRange,int rowCount,int colCount)    {        _range = _sheet.get_Range(startRange,_optionalValue);        _range = _range.get_Resize(rowCount,colCount);        _range.Columns.autoFit();    }    /// <summary>    /// Create header from the propertIEs    /// </summary>    /// <returns></returns>    private object[] Createheader()    {        PropertyInfo[] headerInfo = typeof(T).GetPropertIEs();        // Create an array for the headers and add it to the        // worksheet starting at cell 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;    }    /// <summary>    /// Set header style as bold    /// </summary>    private voID SetheaderStyle()    {        _Font = _range.Font;        _Font.Bold = true;    }    /// <summary>    /// Method to add an excel rows    /// </summary>    /// <param name="startRange"></param>    /// <param name="rowCount"></param>    /// <param name="colCount"></param>    /// <param name="values"></param>    private voID AddExcelRows    (string startRange,int colCount,object values)    {        _range = _sheet.get_Range(startRange,colCount);        _range.set_Value(_optionalValue,values);    }           /// <summary>    /// Create Excel application parameters instances    /// </summary>    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));    }    /// <summary>    /// Release unused COM objects    /// </summary>    /// <param name="obj"></param>    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();        }    }}
总结

以上是内存溢出为你收集整理的c# – 将DataGrid导出为CSV或Excel全部内容,希望文章能够帮你解决c# – 将DataGrid导出为CSV或Excel所遇到的程序开发问题。

如果觉得内存溢出网站内容还不错,欢迎将内存溢出网站推荐给程序员好友。

欢迎分享,转载请注明来源:内存溢出

原文地址: http://outofmemory.cn/langs/1218188.html

(0)
打赏 微信扫一扫 微信扫一扫 支付宝扫一扫 支付宝扫一扫
上一篇 2022-06-05
下一篇 2022-06-05

发表评论

登录后才能评论

评论列表(0条)

保存