如何从c#中插入富文本到excel文件
本文关键字:文本 excel 文件 插入 | 更新日期: 2023-09-27 17:49:34
我需要在excel文件中插入粗体和下划线文本,同时通过c#代码在windows窗体应用程序中保留新行。我的功能如下:
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;
}
此代码不保留新行,粗体,下划线和子弹线。如何做到这一点?由于
如果你的value
有''n'或Environment.NewLine
,也许你可以用这些字符分割它:
string[] newLineChars = { "'n", Environment.NewLine};
string[] splittedVals = value.Split(newLineChars, StringSplitOptions.None);
foreach (string val in splittedVals)
{
mWSheet1.Cells[excelRow, excelColumn] += val;
}