How to insert rich text into excel file from C #
I have a requirement to insert bold and underlined text into an excel file while saving a new line via C # code in a windows form application. My function is like this:
private bool insertIntoExcel(string pathname , string sheetname ,int excelRow, int excelColumn,string value)
{
try
{
Microsoft.Office.Interop.Excel._Application oXL = new Microsoft.Office.Interop.Excel.Application();
oXL.Visible = true;
oXL.DisplayAlerts = false;
Microsoft.Office.Interop.Excel.Workbook mWorkBook = oXL.Workbooks.Open(pathname, 0, false, 5, "", "", false, Microsoft.Office.Interop.Excel.XlPlatform.xlWindows, "", true, false, 0, true, false, false);
//Get all the sheets in the workbook
Microsoft.Office.Interop.Excel.Sheets mWorkSheets = mWorkBook.Worksheets;
//Get the allready exists sheet
Microsoft.Office.Interop.Excel._Worksheet mWSheet1 = (Microsoft.Office.Interop.Excel.Worksheet)mWorkSheets.get_Item(sheetname);
Microsoft.Office.Interop.Excel.Range range = mWSheet1.UsedRange;
mWSheet1.Cells[excelRow, excelColumn] = value;
}catch
{
return false;
}
return true;
}
this code dosen't preserves newline, bold, underscore and bullets. How do you achieve this? Thanks to
+3
source to share
1 answer
if yours value
has "\ n" or Environment.NewLine
maybe you can split it into these characters:
For example:
string[] newLineChars = { "\n", Environment.NewLine};
string[] splittedVals = value.Split(newLineChars, StringSplitOptions.None);
foreach (string val in splittedVals)
{
mWSheet1.Cells[excelRow, excelColumn] += val;
}
0
source to share