C# – Tworzenie pliku Excel.

C# – Tworzenie pliku Excel.

Pokaże teraz jak skonstruować plik Excel w C#. W tym samouczku użyjemy biblioteki Open XML, C# i .NET Core. Zaczynajmy!

  1. Przechodzimy do Visual Studio 2019 i utworzymy nową aplikację konsolową C#.
  2. Musimy dodać odniesienie do biblioteki: DocumentFormat.OpenXml
  3. Dodajemy nową klasę i nazwjemy ja np. Test
  4. I tworzymy publiczną metodę o nazwie CreateExcelDoc. W tej metodzie utworzymy i zapiszemy nasz plik Excel.
  5. Importujemy odpowiednie przestrzenie nazw.
using DocumentFormat.OpenXml;
using DocumentFormat.OpenXml.Packaging;
using DocumentFormat.OpenXml.Spreadsheet;

namespace Pdf
{
    public class Test
    {
        public void CreateExcelDoc(string fileName)
        {
        }
    }
}

6. Teraz tworzymy nowy dokument arkusza kalkulacyjnego i przekazujemy nazwę pliku i dokument jako parametry.

using (SpreadsheetDocument document = SpreadsheetDocument.Create(fileName, SpreadsheetDocumentType.Workbook))
{  }

7. SpreadsheetDocument musi mieć WorkbookPart i WorkSheetPart. Dodamy następujący kod w bloku using.

using (SpreadsheetDocument document = SpreadsheetDocument.Create(fileName, SpreadsheetDocumentType.Workbook))

{
      WorkbookPart workbookPart = document.AddWorkbookPart();
      workbookPart.Workbook = new Workbook();

      WorksheetPart worksheetPart = workbookPart.AddNewPart<WorksheetPart>();
      worksheetPart.Worksheet = new Worksheet(new SheetData());         
}

8. Dołączamy Arkusze do skoroszytu. Arkusze będą zawierać jeden lub wiele arkuszy.

Sheets sheets = workbookPart.Workbook.AppendChild(new Sheets());

9. Następnie możemy dodać jeden lub wiele Arkuszy.

Sheet sheet = new Sheet() { Id = workbookPart.GetIdOfPart(worksheetPart), SheetId = 1, Name = "Arkusz 1" };
sheets.Append(sheet);

10. Na koniec zapis skoroszytu.

workbookPart.Workbook.Save();

11. I teraz w metodzie Main klasy Program utwórzmy obiekt naszej klasy test i wywołajmy metodę CreateExcelDocument, przekazując ścieżkę do pliku.

static void Main(string[] args)
{
     Test test = new Test();
     test.CreateExcelDoc(@"C:\Excel\test.xlsx");
}

12. Uruchommy projekt i sprawdź wygenerowany plik Excel.

13. Jeśli chcemy coś zapisać dodajemy SheetData do arkusza. SheetData działa jak kontener, do którego będą trafiać wszystkie wiersze i kolumny.

SheetData sheetData = worksheetPart.Worksheet.AppendChild(new SheetData());

14. Następnie dodajemy wiersz Row. Klasa Row reprezentuje wiersz w arkuszu kalkulacyjnym programu Excel. Każdy wiersz może zawierać jedną lub więcej komórek Cell. Każda komórka będzie miała CellValue, która zawiera rzeczywistą wartość w komórce.

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

15. Dodaj wiersz do arkusza kalkulacyjnego.

sheetData.AppendChild(row);

I na końcu zapisujemy arkusz.

worksheetPart.Worksheet.Save();

16. Uruchommy projekt i sprawdź wygenerowany plik Excel.

Cały kod klasy Test.

public class Test
{
        public void CreateExcelDoc(string fileName)
        {
            using (SpreadsheetDocument document = SpreadsheetDocument.Create(fileName, SpreadsheetDocumentType.Workbook))
            {
                WorkbookPart workbookPart = document.AddWorkbookPart();
                workbookPart.Workbook = new Workbook();

                WorksheetPart worksheetPart = workbookPart.AddNewPart<WorksheetPart>();
                worksheetPart.Worksheet = new Worksheet();

                Sheets sheets = workbookPart.Workbook.AppendChild(new Sheets());

                Sheet sheet = new Sheet() { Id = workbookPart.GetIdOfPart(worksheetPart), SheetId = 1, Name = "Arkusz 1" };
                sheets.Append(sheet);

                workbookPart.Workbook.Save();

                SheetData sheetData = worksheetPart.Worksheet.AppendChild(new SheetData());
                Row row = new Row();
                Cell cell = new Cell() { CellValue = new CellValue("napis test "), DataType = CellValues.String };
                row.Append(cell);

                sheetData.AppendChild(row);
                worksheetPart.Worksheet.Save();
            }
       }
}

https://github.com/mariuszjurczenko/ExcelOpenXml

55 comments

  1. Cześć. Całkiem ciekawy artykuł. Mam jednak problem z decimalami. Jak można je dodać? DataType = CellValues.Number nie wystarczy i działa tylko na inty.

  2. Some really choice posts on this site, bookmarked . Quintilla Denis Margaux

  3. I have three of these already on my TBR. Great list. Almire Ruy Heeley

  4. This paragraph is in fact a nice one it helps new net viewers, who are wishing for blogging. Elayne Shepard Derriey

  5. Thanks to my father who shared with me about this web site, this website is actually awesome. Babbette Nicolas Wyon Nanine Carey Caldwell

  6. Like!! I blog quite often and I genuinely thank you for your information. The article has truly peaked my interest. Belicia Gerard Mallin

  7. I in addition to my buddies were studying the great helpful tips found on the blog while then came up with an awful feeling I never thanked the web site owner for those tips. My guys became for this reason excited to see all of them and now have pretty much been tapping into these things. Many thanks for genuinely indeed thoughtful as well as for making a decision on this kind of helpful resources millions of individuals are really needing to be aware of. My personal honest regret for not expressing appreciation to earlier. Malynda Timothee Ximenez

  8. Its like you read my mind! You seem to know so much about this, like you wrote the book in it or something. I think that you can do with some pics to drive the message home a little bit, but other than that, this is magnificent blog. A great read. I will definitely be back. Tami Lyle Farrica

  9. Appreciating the dedication you put into your blog and in depth information you provide. Wynny Reinald Theron

  10. Having read this I believed it was rather informative. I appreciate you finding the time and energy to put this information together. I once again find myself spending a lot of time both reading and posting comments. But so what, it was still worth it! Mari Derron Chadburn

  11. Wow, this post is pleasant, my younger sister is analyzing these kinds of things, therefore I am going to tell her.| Gwenore Morgun Penrose

  12. This site is my inhalation, real fantastic layout and Perfect subject matter. Joellen Gonzales Cordula Elmira Rubin Lehmann

  13. Hiya, I am really glad I have found this information. Today bloggers publish only about gossip and web stuff and this is really annoying. A good website with interesting content, this is what I need. Thanks for making this site, and I will be visiting again. Do you do newsletters by email? Allina Ralph Charline

  14. I have read a few good stuff here. Definitely worth bookmarking for revisiting. I surprise how much effort you put to create such a magnificent informative site. Rosabel Augustus Clapper

  15. I enjoy you because of all of your effort on this web site. My mother enjoys making time for investigation and it is simple to grasp why. We know all of the powerful medium you provide effective tips on the blog and as well foster contribution from other people on this concern then our favorite child has always been becoming educated a great deal. Take advantage of the rest of the year. Your carrying out a stunning job. Ashli Kermy Simdars

  16. I have learn some good stuff here. Definitely worth bookmarking for revisiting. I surprise how so much attempt you set to make this type of fantastic informative website. Nathalia Roderic Naldo

  17. I feel genuinely thrilled to have seen your current webpage and appearance forward to be able to so many more interesting times reading here. Cheers yet again for all typically the details. Beilul Hersh Jollenta

  18. Thanks-a-mundo for the blog article. Really looking forward to read more. Engracia Elden Edouard Ivette Hillier Intosh

  19. Great site. Plenty of helpful information here. I am sending it to several buddies ans additionally sharing in delicious. And naturally, thank you for your sweat! Cari Ryan Claudell

  20. Touche. Outstanding arguments. Keep up the great spirit.| Anderea Odey Peggy

  21. Hello, I enjoy readinhg all off you post. I wanted to write a little comment to support you. Morganica Timothy Ruperto

  22. Major thanks for the blog. Much thanks again. Want more. Arlena Orrin Aubarta

  23. I blog quite often and I truly appreciate your information. Your article has truly peaked my interest. I will book mark your site and keep checking for new information about once per week. I opted in for your Feed too. Renate Byram Braynard

  24. Excellent, what a web site it is! This web site gives useful facts to us, keep it up. Yolanthe Rockey Compton

  25. Well I really enjoyed reading it. This tip provided by you is very constructive for accurate planning. Fernanda Lenard Oliy Ophelia Zolly Flinn

  26. Kakalina Woodrow Maximilien pisze:

    Twoja metoda wyjaśniania wszystkiego w tym artykule jest naprawdę przyjemna, wszyscy mogą to łatwo zrozumieć. Wielkie dzięki.

  27. Po przejrzeniu kilku postów na blogu w Twojej witrynie, szczerze doceniam Twój sposób pisania bloga. Dokonałem rezerwacji i oznaczyłem to na mojej liście zakładek i wrócę w najbliższej przyszłości.

  28. Doskonały post. Absolutnie doceniam tę stronę. Pisz dalej! Eleanora Mal Mathis

  29. I’ve been browsing online greater than 3 hours as of late, but I by no means discovered any attention-grabbing article like yours.
    It is lovely price enough for me. Personally, if all web owners and bloggers made excellent content as you probably did, the net can be
    much more helpful than ever before.

  30. Jesteś inspiracją dla wielu, którzy dopiero zaczynają swoją przygodę z dziedziną

  31. Nice blog! Thanks you all star articles good story!

  32. Doceniam twoje teksty i prawie wszystkie chłonę migiem, dziękuję za link z komentarza, on jest rankingowym dźwigiem.

  33. Mam pytanie dotyczące [konkretnego fragmentu] artykułu. Czy możesz to wyjaśnić bardziej szczegółowo

  34. Bardzo mi się podoba, jak zastosowano [omawianą technologię/metodologię] w praktyce. Przejrzyste wyjaśnienie z przykładami ułatwia zrozumienie.

  35. Bardzo ciekawe podejście do tematu. Zawsze warto patrzeć na to z różnych perspektyw

  36. Jestem pod wrażeniem, jak potrafisz przekazywać informacje w sposób, który angażuje czytelnika od pierwszego zdania.

  37. curso de mecânica online pisze:

    Dzięki za podkreślenie kluczowych aspektów [tematu]! To naprawdę pomogło mi zrozumieć istotę tego zagadnienia

  38. Dzięki temu artykułowi zacząłem zastanawiać się nad [tematem] zupełnie inaczej. Naprawdę wartościowe spojrzenie

  39. Hair transplant before-after pisze:

    Bardzo doceniam, że zawsze dostarczasz źródła i dodatkowe materiały do pogłębienia wiedzy

  40. Şükür Kurbanı Nedir? Şükür Kurbanı Ne Zaman Kesilir? pisze:

    Dzięki za dzielenie się swoją wiedzą. To naprawdę cenione

  41. VPS SERVER
    Высокоскоростной доступ в Интернет: до 1000 Мбит/с
    Скорость подключения к Интернету — еще один важный фактор для успеха вашего проекта. Наши VPS/VDS-серверы, адаптированные как под Windows, так и под Linux, обеспечивают доступ в Интернет со скоростью до 1000 Мбит/с, что гарантирует быструю загрузку веб-страниц и высокую производительность онлайн-приложений на обеих операционных системах.

  42. https://medium.com/@vivienne2274/ультра-быстрый-выделенный-сервер-с-ssd-накопителями-3fb2ebe42fb4
    VPS SERVER
    Высокоскоростной доступ в Интернет: до 1000 Мбит/с
    Скорость подключения к Интернету — еще один важный фактор для успеха вашего проекта. Наши VPS/VDS-серверы, адаптированные как под Windows, так и под Linux, обеспечивают доступ в Интернет со скоростью до 1000 Мбит/с, что гарантирует быструю загрузку веб-страниц и высокую производительность онлайн-приложений на обеих операционных системах.

Dodaj komentarz

Twój adres e-mail nie zostanie opublikowany. Wymagane pola są oznaczone *