Loading
Know the answer? Post it. Somebody with the same question will find it here.
Answer a question in the forums and earn +20 SHARP for every answer.
See unanswered questions
DevSocialUpcoming · 3rd editionAI Agents ConferenceDec 1–3, 2026Live onlineFree to attend5days leftRegister
Adarsh NigamRank #950 · 2.1K reputationPosted Aug 6, 2024, 4:22 AM EDT
Creating an XLSX file in C# without using any third-party libraries or Microsoft Office Interop is possible by working with the Open XML format, which is the native format for Excel files since Excel 2007. This can be done by generating the necessary XML structure manually and then saving it as an
.xlsxfile. Here's a basic example of how you can do this:Steps to Create XLSX Manually in C#
Create the Required XML Parts:
Package the Parts Together:
.zipfile and then rename it to.xlsx.using System; using System.IO; using System.IO.Compression; using System.Text; class Program { static void Main() { // Create the necessary folders for the XLSX file structure string folderPath = "ExcelFile"; Directory.CreateDirectory(folderPath); Directory.CreateDirectory(Path.Combine(folderPath, "_rels")); Directory.CreateDirectory(Path.Combine(folderPath, "xl")); Directory.CreateDirectory(Path.Combine(folderPath, "xl", "worksheets")); // Create [Content_Types].xml string contentTypesXml = @" "; File.WriteAllText(Path.Combine(folderPath, "[Content_Types].xml"), contentTypesXml); // Create .rels file string relsXml = @" "; File.WriteAllText(Path.Combine(folderPath, "_rels", ".rels"), relsXml); // Create workbook.xml string workbookXml = @" "; File.WriteAllText(Path.Combine(folderPath, "xl", "workbook.xml"), workbookXml); // Create sheet1.xml string sheet1Xml = @" Hello World "; File.WriteAllText(Path.Combine(folderPath, "xl", "worksheets", "sheet1.xml"), sheet1Xml); // Create the zip file (XLSX file) string xlsxPath = "Output.xlsx"; if (File.Exists(xlsxPath)) { File.Delete(xlsxPath); } ZipFile.CreateFromDirectory(folderPath, xlsxPath); // Clean up temporary files Directory.Delete(folderPath, true); Console.WriteLine("XLSX file created successfully."); } }Explanation:
[Content_Types].xmlspecifies the content types..relsfile manages relationships.workbook.xmldefines the workbook structure, andsheet1.xmlholds the data..xlsxfile.Limitations:
This approach allows you to create a basic Excel file programmatically in C# without relying on third-party libraries or Office Interop.
Riya52 reputationPosted Aug 6, 2024, 4:35 AM EDT
Thanks. Creating the xlsx file but its corrupted. Also is it possible to fill the datatable data into this excel code?