导出时DatagridView不会在同一单元格中换行

时间:2018-11-01 13:48:27

标签: c# datagridview

如您在图片中看到的: 在Datagridview中,我断开了行,但是在导出为ex​​cel时,行被断开到下面的单元格中。

我需要它在同一单元格中打断行

 dataGridView1.Columns[0].DefaultCellStyle.WrapMode = DataGridViewTriState.True;
 dataGridView1.Columns[1].DefaultCellStyle.WrapMode = DataGridViewTriState.True;

 dataGridView1.DefaultCellStyle.WrapMode = DataGridViewTriState.True;
 dataGridView1.AutoSizeRowsMode = DataGridViewAutoSizeRowsMode.AllCells;
 dataGridView1.AutoSizeColumnsMode = DataGridViewAutoSizeColumnsMode.None;

在网格中,它正在正常工作,例如我收到的字符串的示例:

"Ao sol da manhã\r\n uma gota de orvalho\r\n precioso diamante."

导出到Excel时,不会在“相同”单元格中中断文本,而在底行则中断。 enter image description here

private void button2_Click(object sender, EventArgs e)
{
    copyAlltoClipboard();
    Microsoft.Office.Interop.Excel.Application xlexcel;
    Microsoft.Office.Interop.Excel.Workbook xlWorkBook;
    Microsoft.Office.Interop.Excel.Worksheet xlWorkSheet;
    object misValue = System.Reflection.Missing.Value;
    xlexcel = new Microsoft.Office.Interop.Excel.Application();
    xlexcel.Visible = true;
    xlWorkBook = xlexcel.Workbooks.Add(misValue);
    xlWorkSheet = (Microsoft.Office.Interop.Excel.Worksheet)xlWorkBook.Worksheets.get_Item(1);
    Microsoft.Office.Interop.Excel.Range CR = (Microsoft.Office.Interop.Excel.Range)xlWorkSheet.Cells[1, 1];
   // Qubra de linha
   // xlWorkSheet.Range["B1:B500"].Cells.WrapText = true;
    xlWorkSheet.Columns[2].Cells.WrapText = true;
    xlWorkSheet.Columns[2].ColumnWidth += 15;
    //xlWorkSheet.Columns[2].AutoFit();
    xlWorkSheet.Columns[2].Cells.WrapText = true;
    xlWorkSheet.Columns[2].Style.WrapText = true;
    xlWorkSheet.Cells[8, 2].Style.WrapText = true;
    xlWorkSheet.Cells[9, 2].Style.WrapText = true;
    xlWorkSheet.Cells[10, 2].Style.WrapText = true;
    xlWorkSheet.Columns[2].WrapText = true;
    //Set Text-Wrap for all rows true//
    xlWorkSheet.Rows.WrapText = true;
    CR.Select();
    xlWorkSheet.PasteSpecial(CR, Type.Missing, Type.Missing, Type.Missing, Type.Missing, Type.Missing, true);          
}

如您所见,将文本拆分为excel时,它不是在同一单元格内被拆分,而是在新行中被拆分。我该怎么解决?

1 个答案:

答案 0 :(得分:0)

Please Change last line of your code (PasteSpecial) and try below code.
please use Row and column variables as per your code.

Microsoft.Office.Interop.Excel.Range PastToRange =
oExcel.CreateRange(row,FromCol,ToCol,ToRow,TmpWorkSheet);
PastToRange.PasteSpecial(Microsoft.Office.Interop.Excel.XlPasteType.xlPasteAll,
Microsoft.Office.Interop.Excel.XlPasteSpecialOperation.xlPasteSpecialOperationNone,
false, false);