使用回车导出到Excel

时间:2014-11-11 16:15:09

标签: c# wpf excel datagrid

我正在尝试从Datagrid导出到Excel。 Datagrid有一个列,我们在其中放入注释。在该列中,注释放在不同的行中。当它导出到excel时,它会以多行导出。

以下是我DataGrid中的内容:

Data Grid

以下是导出到Excel时的外观:

Excel  Export

以下是我用来执行此操作的代码:

public static void CreateExcelFromClipboard(string worksheetName, string fullFilePath, bool toOpen)
        {
            //Excel Application class 
            _Application app = new Microsoft.Office.Interop.Excel.Application();

            //Get process id
            int excelProcessId = GetApplicationProcessId(app);

            try
            {
                //Add workbook
                Workbook theWorkbook = app.Workbooks.Add(XlWBATemplate.xlWBATWorksheet);
                //Add worksheet
                var theWorksheet =
                    (Worksheet)theWorkbook.Worksheets.Add(Type.Missing, Type.Missing, Type.Missing, Type.Missing);
                theWorksheet.Name = worksheetName;
                app.SheetsInNewWorkbook = 1;
                app.DisplayAlerts = false;
                theWorksheet.Activate();

                //Paste to the worksheet from clpboard
                theWorksheet.Paste(Type.Missing, Type.Missing);

                //Apply Borders
                ApplyBorder(theWorksheet.UsedRange);

                //Auto Fit All columns
                Range xlRange = theWorksheet.UsedRange;
                // put all hardcodes in  a constant class 
                xlRange.Font.Name = "Arial";
                xlRange.Font.Size = 9;
                var firstRowRange = (Range)xlRange.Rows[1, Missing.Value];
                firstRowRange.EntireRow.Font.Bold = true;
                firstRowRange.EntireRow.HorizontalAlignment = XlHAlign.xlHAlignCenter;
                //Set Wrap Test to false
                xlRange.WrapText = true;
                xlRange.Columns.AutoFit();
                theWorksheet.Activate();

                //Save the file
                theWorkbook.SaveAs(fullFilePath, XlFileFormat.xlOpenXMLWorkbook, Type.Missing, Type.Missing,
                                   Type.Missing, Type.Missing, XlSaveAsAccessMode.xlNoChange,
                                   Type.Missing, Type.Missing, Type.Missing, Type.Missing, Type.Missing);
                if (!toOpen)
                {
                    //Clean up 
                    app.Quit();
                    Marshal.ReleaseComObject(app);
                }
            }
            catch
            {
                ForceExcelClose(excelProcessId);
                throw;
            }
            finally
            {
                app.Visible = toOpen;
            }
        }

0 个答案:

没有答案