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

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

35 comments

  1. Dzień dobry. Ten artykuł był niezwykle fascynujący, zwłaszcza że w zeszły wtorek szukałem przemyśleń na ten temat. Britteny Richard Mima

  2. Naprawdę doceniam udostępnienie tego artykułu na blogu. Naprawdę nie mogę się doczekać, aby przeczytać więcej. Fajne. Ginnie Husain Turoff

  3. I always emailed this weblog post page to all my associates, for the reason that if like to read it after that my contacts will too.| Addie Emmy Matias

  4. 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

  5. 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

  6. You need to be a part of a contest for one of the greatest websites online. I am going to highly recommend this web site! Shela Bradley Lewendal

  7. 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

  8. 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

  9. Everything is very open with a clear clarification of the issues. It was really informative. Your site is useful. Thanks for sharing! Pippa Eldin Janek

  10. 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

  11. 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