🔥 Zapisy zamknięte, ale możesz pobrać Roadmapę .NET i dołączyć do listy oczekujących — Pobierz i dołącz do Listy VIP →

Plik Excel w C# cz.2 — stylowanie komórek

C# – Tworzenie pliku Excel. część 2.

Dodamy teraz arkusz stylów do Exela. Utworzymy nową metodę GenerateStylesheet(), która zwraca obiekt StyleSheet.

private Stylesheet GenerateStylesheet()
{
   Stylesheet styleSheet = null;   
   return styleSheet;
}

Utworzymy teraz Czcionki – Fonty.

Czcionki mogą mieć jedno lub więcej elementów podrzędnych Font, z których każdy ma inne właściwości, takie jak FontSize, Bold, Color itp. Dodamy teraz kod w metodzie GenerateStyleSheet:

Fonts fonts = new Fonts(
    new Font( 
       new FontSize() { Val = 10 }
    ),
    new Font( 
        new FontSize() { Val = 14 },
        new Bold(),
        new Color() { Rgb = "FFFFFF" }
    )
);

Zwróć uwagę, że dodajemy dwa elementy podrzędne Font do obiektu Fonts. Pierwszy z nich to domyślna czcionka używana przez wszystkie komórki, a druga jest specyficzna dla nagłówka.

Teraz dodamy wypełnienie.

Wypełnienia mogą mieć co najmniej jeden element podrzędny Fill, dla którego można ustawić jego kolor ForegroundColor.

Fills fills = new Fills(
   new Fill(new PatternFill() { PatternType = PatternValues.None }),
   new Fill(new PatternFill() { PatternType = PatternValues.Gray125 }),             
   new Fill(new PatternFill(new ForegroundColor { Rgb = new HexBinaryValue() { Value = "66666666" } }) { PatternType = PatternValues.Solid })
);

Excel musi mieć domyślnie pierwsze dwa. Trzeci to styl, jaki chcemy mieć dla naszych komórek nagłówkowych; szare pogrubione tło.

Teraz obramowania – Borders.

Obramowania mogą mieć jedno lub więcej elementów podrzędnych Border, z których każde określa, jak powinno wyglądać obramowanie:

Borders borders = new Borders(
   new Border(),
   new Border(
       new LeftBorder(new Color() { Auto = true }) { Style = BorderStyleValues.Dotted },
       new RightBorder(new Color() { Auto = true }) { Style = BorderStyleValues.Dotted },
       new TopBorder(new Color() { Auto = true }) { Style = BorderStyleValues.Thin },
       new BottomBorder(new Color() { Auto = true }) { Style = BorderStyleValues.Thin },
       new DiagonalBorder())
);

Pierwsza to ramka domyślna, a druga to nasza niestandardowa ramka.

CellFormats

Teraz, gdy ustawilismy nasze niestandardowe formatowanie, możemy utworzyć CellFormats, które mają jedno lub wiele elementów potomnych CellFormat. A Każdy CellFormat otrzymuje indeks Czcionki, Obramowania, Wypełnienie itp. Z którym będzie skojarzony:

CellFormats cellFormats = new CellFormats(
   new CellFormat(),
   new CellFormat { FontId = 0, FillId = 0, BorderId = 1, ApplyBorder = true }, 
   new CellFormat { FontId = 1, FillId = 2, BorderId = 1, ApplyFill = true }
);

Na koniec inicjalizujemy obiekt Stylesheet:

styleSheet = new Stylesheet(fonts, fills, borders, cellFormats);

Teraz możemy dodać styl do skoroszytu.

WorkbookStylesPart stylePart = workbookPart.AddNewPart<WorkbookStylesPart>();
stylePart.Stylesheet = GenerateStylesheet();
stylePart.Stylesheet.Save();

Dodajemy styl do komórek

Teraz, gdy mamy dodany styl do skoroszytu, możemy określić, jaki styl ma posiadać każda komórka. Każda Cell ma właściwość o nazwie StyleIndex, która pobiera indeks stylu, który chcemy zastosować do tej komórki. Modyfikujemy i przekazujemy pożądany indeks stylu:

Row row = new Row();
   row.Append(new Cell() { CellValue = new CellValue("napis test "), DataType = CellValues.String, StyleIndex = 2 },
       new Cell() { CellValue = new CellValue("napis test "), DataType = CellValues.String, StyleIndex = 2 },
       new Cell() { CellValue = new CellValue("napis test "), DataType = CellValues.String, StyleIndex = 2 });

    sheetData.AppendChild(row);

    for (int i = 0; i < 20; i++)
    {
       row = new Row();
       row.Append(new Cell() { CellValue = new CellValue("napis test " + i), DataType = CellValues.String, StyleIndex = 1 },
          new Cell() { CellValue = new CellValue("napis test " + i), DataType = CellValues.String, StyleIndex = 1 },
          new Cell() { CellValue = new CellValue("napis test " + i), DataType = CellValues.String, StyleIndex = 1 },
          new Cell() { CellValue = new CellValue("napis test " + i), DataType = CellValues.String, StyleIndex = 1 },
          new Cell() { CellValue = new CellValue("napis test "), DataType = CellValues.String, StyleIndex = 1 },
          new Cell() { CellValue = new CellValue("napis test " + i), DataType = CellValues.String, StyleIndex = 1 },
          new Cell() { CellValue = new CellValue("napis test "), DataType = CellValues.String, StyleIndex = 1 },
          new Cell() { CellValue = new CellValue("napis test " + i), DataType = CellValues.String, StyleIndex = 1 },
          new Cell() { CellValue = new CellValue("napis test "), DataType = CellValues.String, StyleIndex = 1 });

    sheetData.AppendChild(row);
}

Możemy dodać niestandardową szerokość kolumn.

Columns columns = new Columns(
        new Column 
        {
            Min = 1,
            Max = 1,
            Width = 30,          
            CustomWidth = true      
        },
        new Column 
        {
            Min = 2,
            Max = 5,
            Width = 20,
            CustomWidth = true
        },
        new Column 
        {
            Min = 6,
            Max = 6,
            Width = 40,
            CustomWidth = true
        }
        ...
        );

Na koniec musimy dołączyć kolumny do arkusza roboczego.

workheetPart.Worksheet.AppendChild(columns);

Uruchom aplikację i sprawdź wygenerowany plik Excel!

https://github.com/mariuszjurczenko/ExcelOpenXml

Powiązane: to część 2 z 3 — wróć do tworzenia pliku Excel (część 1) lub przejdź do wykresu słupkowego (część 3). Zobacz też generowanie dokumentów w C#.

👨‍💻
Mariusz Jurczenko
Senior .NET Developer · 10+ lat doświadczenia komercyjnego

Programista .NET z doświadczeniem komercyjnym w firmach takich jak NFZ, Kamsoft, Diagnostyka, Hermes Reply Polska czy Etisoft Smart Solutions. Twórca kursów, z których skorzystało już ponad 11 000 osób w Strefie Kursów i ponad 1 000 kursantów na dev-hobby.pl.

Specjalizacja: Clean Code, Clean Architecture i uczenie programowania tak, żeby dało się je naprawdę zrozumieć — nie wykuć.

🚀 Co dalej?

Zobacz to w praktyce na wideo i pobierz darmową roadmapę, żeby ułożyć naukę w spójną ścieżkę do pierwszej pracy.

36 comments

  1. Hi there, simply changed into alert to your weblog thru Google, and found that it is truly informative. I am gonna watch out for brussels. I will be grateful if you happen to proceed this in future. Numerous folks shall be benefited from your writing. Cheers!| Laurene Coop Avron

  2. I simply wanted to construct a simple remark so as to appreciate you for those remarkable tips and tricks you are showing here. My incredibly long internet research has at the end of the day been compensated with really good suggestions to write about with my family members. I would claim that many of us website visitors are really endowed to exist in a fantastic website with many perfect people with useful advice. I feel extremely fortunate to have used your entire web site and look forward to some more enjoyable times reading here. Thanks once more for everything. Elva Launce Souza

  3. Write more, thats all I have to say. Literally, it seems as though you relied on the video to make your point. You obviously know what youre talking about, why throw away your intelligence on just posting videos to your blog when you could be giving us something informative to read? Britney Tobin Gentry

  4. Pretty section of content. I just stumbled upon your web site and in accession capital to assert that I get in fact enjoyed account your blog posts. Any way I will be subscribing to your feeds and even I achievement you access consistently quickly. Savina Lyell Dallon

  5. After looking at a handful of the blog articles on your website, I really appreciate your technique of writing a blog. I saved as a favorite it to my bookmark site list and will be checking back soon. Please visit my website too and let me know how you feel. Nonna Mendy Shieh

  6. You actually make it seem so easy along with your presentation having
    said that i find this topic to get really something that I do
    believe I might never understand. It appears too complex and very broad for me personally.
    I’m anticipating for your forthcoming post, I will try to get the hang from it!

Dodaj komentarz

czytanie to początek

Zamień wiedzę w umiejętności

Pobierz darmową Roadmapę .NET i ułóż takie tematy jak ten w spójną ścieżkę do pierwszej pracy.

Pobieram roadmapę →