导出到excel时,当我的一个数据源单元格包含换行符(回车符)时,每个数据源行会出现空白或多行。我想阻止这一点。
这是我用来创建工作簿并粘贴数据的代码:
//Copy to clipboard
DGVJobList.ClipboardCopyMode = DataGridViewClipboardCopyMode.EnableAlwaysIncludeHeaderText;
DGVJobList.SelectAll();
DataObject DO = DGVJobList.GetClipboardContent();
Clipboard.SetDataObject(DO);
DGVJobList.ClearSelection();
//Create Excel Workbook and Paste
Excel.Application XLApp = new Excel.Application();
Excel.Workbook XLWorkBook;
Excel.Worksheet XLWorkSheet;
object misValue = System.Reflection.Missing.Value;
XLWorkBook = XLApp.Workbooks.Add(misValue);
XLWorkSheet = (Excel.Worksheet)XLWorkBook.Worksheets.get_Item(1);
Excel.Range XLRange = (Excel.Range)XLWorkSheet.Cells[1, 1];
XLRange.Select();
XLWorkSheet.PasteSpecial(XLRange, Type.Missing, Type.Missing, Type.Missing, Type.Missing, Type.Missing, true);
答案 0 :(得分:0)
通过从DGVJobList创建2D数据数组,您可以更好地控制数据放置,而不是使用剪贴板。然后,创建对相同尺寸的Excel范围的引用并设置其值。此示例仅显示用于说明的通用2D阵列。您可以构建2D数组,以便按照自己的方式布局数据。
//Build data as 2D array
int[,] array2D = new int[,] { { 1, 2 }, { 3, 4 }, { 5, 6 }, { 7, 8 } };
//Create Excel Workbook and Paste
Excel.Application XLApp = new Excel.Application();
Excel.Workbook XLWorkBook;
Excel.Worksheet XLWorkSheet;
object misValue = System.Reflection.Missing.Value;
XLWorkBook = XLApp.Workbooks.Add(misValue);
XLWorkSheet = (Excel.Worksheet)XLWorkBook.Worksheets.get_Item(1);
//Use range same size as data
Excel.Range XLRange = (Excel.Range) XLWorkSheet.Range["A1", "B4"];
XLRange.Value = array2D;