如何使用EPplus在excel中获得部分单元格样式?

时间:2014-02-19 14:54:28

标签: c# excel epplus

我有一个单元格,其中有一些斜体文字,一些文字没有斜体字。如何保留格式?我查看了OfficeOpenXml.Style.ExcelStyle,看到悬挂的选项是否为粗体,斜体等,但这些选项适用于整个单元格。有没有办法告诉哪个文本使用eppplus以某种方式格式化并保留格式?

    FileInfo info = new FileInfo(@"C:\excel.xlsx");
        using (ExcelPackage package = new ExcelPackage(info)) {
            ExcelWorksheet sheet = package.Workbook.Worksheets["Sheet"];
            object text = sheet.Cells[1, 1].Value;

            // if I do toString, I lose all formatting:
            string textWithOutFormat = text.ToString();
            // I would assume I'd get it some how like this?
            if (sheet.Cells[1, 1].IsRichText) {
                // get rich text formatting or get what items are wrapp in rich text
                // no idea how to get it.
            }
        }

1 个答案:

答案 0 :(得分:4)

要编写具有多种样式的单元格:

FileInfo fi = new FileInfo(@"c:\File.xlsx");

using (ExcelPackage package = new ExcelPackage(fi))
{

    ExcelWorksheet worksheet = package.Workbook.Worksheets["Sheets"];

    worksheet.Cells[1, 1].IsRichText = true;
    ExcelRichText richtext = worksheet.Cells[1, 1].RichText.Add("Test Italic");
    richtext .Italic = true;

    richtext = worksheet.Cells[1, 1].RichText.Add("Test 2");
    richtext .Italic = false;

    package.Save();
}

要读取具有多种样式的单元格:

foreach(var part in cell.RichText)
 {
   if (part.Bold)
    // Do staff

   if (part.Italic)
    // Do staff

 }