Warning: file_get_contents(/data/phpspider/zhask/data//catemap/4/wpf/12.json): failed to open stream: No such file or directory in /data/phpspider/zhask/libs/function.php on line 167

Warning: Invalid argument supplied for foreach() in /data/phpspider/zhask/libs/tag.function.php on line 1116

Notice: Undefined index: in /data/phpspider/zhask/libs/function.php on line 180

Warning: array_chunk() expects parameter 1 to be array, null given in /data/phpspider/zhask/libs/function.php on line 181
C# 将WPF数据网格导出到Excel_C#_Wpf_Excel_Datagrid - Fatal编程技术网

C# 将WPF数据网格导出到Excel

C# 将WPF数据网格导出到Excel,c#,wpf,excel,datagrid,C#,Wpf,Excel,Datagrid,当我将DataGrid导出到Excel时,为什么我的值会发生变化 字符串351732051316944变为351732E+14 我的约会时间: 2014-01-01 02:09:29.942变为4164109035 我怎样才能让它停止 我用来导出到Excel的类 public class ExportToExcel<T> { public List<T> dataToPrint; // Excel object references. privat

当我将DataGrid导出到Excel时,为什么我的值会发生变化

字符串351732051316944变为351732E+14

我的约会时间: 2014-01-01 02:09:29.942变为4164109035

我怎样才能让它停止

我用来导出到Excel的类

public class ExportToExcel<T>
{
    public List<T> dataToPrint;
    // Excel object references.
    private Microsoft.Office.Interop.Excel.Application excelApp = null;
    private Workbooks books = null;
    private Workbook book = null;
    private Sheets sheets = null;
    private Worksheet sheet = null;
    private Range range = null;
    private Font font = null;
    // Optional argument variable
    private object optionalValue = Missing.Value;


    /// Generate report and sub functions
    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);
        }
    }
    /// Make Microsoft Excel application visible
    private void OpenReport()
    {
        excelApp.Visible = true;
    }
    /// Populate the Excel sheet
    private void FillSheet()
    {
        object[] header = CreateHeader();
        WriteData(header);
    }
    /// Write data into the 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);
    }
    /// Method to make columns auto fit according to data
    private void AutoFitColumns(string startRange, int rowCount, int colCount)
    {
        range = sheet.get_Range(startRange, optionalValue);
        range = range.get_Resize(rowCount, colCount);
        range.Columns.AutoFit();
    }
    /// Create header from the properties
    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;
    }
    /// Set Header style as bold
    private void SetHeaderStyle()
    {
        font = range.Font;
        font.Bold = true;
    }
    /// Method to add an excel rows
    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);
    }

    /// Create Excel application parameters instances
    private void CreateExcelRef()
    {
        excelApp = new Microsoft.Office.Interop.Excel.Application();
        books = (Workbooks)excelApp.Workbooks;
        book = (Workbook)(books.Add(optionalValue));
        sheets = (Sheets)book.Worksheets;
        sheet = (Worksheet)(sheets.get_Item(1));
    }

    /// Release unused COM objects
    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();
        }
    }
}
公共类ExportToExcel
{
公共列表数据打印;
//Excel对象引用。
私有Microsoft.Office.Interop.Excel.Application excelApp=null;
私人工作簿=空;
私人工作簿=null;
私有表=空;
专用工作表=空;
私有范围=空;
私有字体=null;
//可选参数变量
私有对象optionalValue=缺少.Value;
///生成报告和子功能
公共无效生成器报告()
{
尝试
{
if(dataToPrint!=null)
{
如果(dataToPrint.Count!=0)
{
鼠标.SetCursor(Cursors.Wait);
CreateExcelRef();
FillSheet();
OpenReport();
鼠标.SetCursor(游标.Arrow);
}
}
}
捕获(例外e)
{
MessageBox.Show(“生成Excel报告时出错”);
}
最后
{
释放对象(张);
释放对象(张);
发布对象(书);
发布对象(书籍);
发布对象(excelApp);
}
}
///使Microsoft Excel应用程序可见
私有void OpenReport()
{
excelApp.Visible=true;
}
///填充Excel工作表
专用空白填充页()
{
object[]header=CreateHeader();
写入数据(标题);
}
///将数据写入Excel工作表
私有void WriteData(对象[]头)
{
object[,]objData=新对象[dataToPrint.Count,header.Length];
对于(int j=0;j

我不知道从何处开始解决这个问题,但是非常感谢您的帮助

如果您必须像这样使用Excel automation,那么您需要确保对单元格应用正确的格式。因此,在设置值之后,还要设置格式。例如,日期可以是:

range.set_Value(optionalValue, values);
range.NumberFormat = "dd-mmm-yyyy";
为了防止使用您提到的格式显示数字:

range.set_Value(optionalValue, values);
range.NumberFormat = "0";

不要使用Excel automation,而是使用一个库,Nuget上有很多。你有更喜欢的库吗?我使用ePlus