OpenXML更改搜索的文本单元格颜色

时间:2018-10-10 03:39:28

标签: c# openxml

我已经看过几篇文章,以更改特定文本(单元格)的颜色,但无法理解。有什么简单的方法吗?我只想在OpenXML中更改特定文本(单元格)的颜色 这是我的代码:

    using DocumentFormat.OpenXml;
    using DocumentFormat.OpenXml.Packaging;
    using DocumentFormat.OpenXml.Spreadsheet;



    private void HighlightDoc()
        {
byte[] byteArray = File.ReadAllBytes(@"C:\TestArea\Destination\SUP000011\ATM-1B4L2KQ0ZE0-0001\TestExcel.xlsx");
        using (MemoryStream ms = new MemoryStream())
        {
            ms.Write(byteArray, 0, (int)byteArray.Length);
            using (SpreadsheetDocument doc = SpreadsheetDocument.Open(ms, true))
              {
           Sheet sheet = doc.WorkbookPart.Workbook.Descendants<Sheet>().First<Sheet>();
          Worksheet worksheet = ((WorksheetPart)doc.WorkbookPart.GetPartById(sheet.Id)).Worksheet;
        IEnumerable<DocumentFormat.OpenXml.Spreadsheet.Row> allRows = worksheet.GetFirstChild<SheetData>().Descendants<DocumentFormat.OpenXml.Spreadsheet.Row>();
     foreach (DocumentFormat.OpenXml.Spreadsheet.Row currentRow in allRows)
      {
                                    IEnumerable<DocumentFormat.OpenXml.Spreadsheet.Cell> allCells = currentRow.Descendants<DocumentFormat.OpenXml.Spreadsheet.Cell>();
    foreach (DocumentFormat.OpenXml.Spreadsheet.Cell currentCell in allCells)
    {
       CellValue currentCellValue = currentCell.GetFirstChild<CellValue>();
       string data = null;
       if (currentCell.DataType != null)
        {
         if (currentCell.DataType == CellValues.SharedString) // cell has a cell value that is a string, thus, stored else where
      {
        data = doc.WorkbookPart.GetPartsOfType<SharedStringTablePart>().FirstOrDefault().SharedStringTable.ElementAt(int.Parse(currentCellValue.Text)).InnerText;
              if (data == "John")
             {
                      //Code to change cell colour
              }
           }
        }
        else
            {
                  data = currentCellValue.Text;


                                        }

                                    }
                                }

                            }
                            // Convert it to byte array 

                            byte[] bytesInStream = ms.ToArray();
                            if (bytesInStream != null)
                            {
                                Response.AppendHeader("content-disposition",
                                        "inline; filename=" + "yourExcelFileName.xlsx");
                                Response.AddHeader("content-length", bytesInStream.Length.ToString());
                                Response.BinaryWrite(bytesInStream);
                                Response.End();
                            }
                        }


                    }

0 个答案:

没有答案