Create a spreadsheet document by a file name

  • OpenXML SDK
  • Spire.XLS
  • Download Sample Code

class Program
    {
        static void Main(string[] args)
        {
            CreateSpreadsheetWorkbook(@"..\..\Documents\Sheet2.xlsx");
        }
        public static void CreateSpreadsheetWorkbook(string filepath)
        {
            // Create a spreadsheet document by supplying the filepath.
            // By default, AutoSave = true, Editable = true, and Type = xlsx.
            SpreadsheetDocument spreadsheetDocument = SpreadsheetDocument.Create(filepath, SpreadsheetDocumentType.Workbook);

            // Add a WorkbookPart to the document.
            WorkbookPart workbookpart = spreadsheetDocument.AddWorkbookPart();
            workbookpart.Workbook = new Workbook();

            // Add a WorksheetPart to the WorkbookPart.
            WorksheetPart worksheetPart = workbookpart.AddNewPart();
            worksheetPart.Worksheet = new Worksheet(new SheetData());

            // Add Sheets to the Workbook.
            Sheets sheets = spreadsheetDocument.WorkbookPart.Workbook.
                AppendChild(new Sheets());

            // Append a new worksheet and associate it with the workbook.
            Sheet sheet = new Sheet()
            {
                Id = spreadsheetDocument.WorkbookPart.
                GetIdOfPart(worksheetPart),
                SheetId = 1,
                Name = "mySheet"
            };
            sheets.Append(sheet);

            workbookpart.Workbook.Save();

            // Close the document.
            spreadsheetDocument.Close();
        }
    }

class Program
    {
        static void Main(string[] args)
        {
            CreateSpreadsheetWorkbook(@"..\..\Documents\Sheet2.xlsx");
        }
        public static void CreateSpreadsheetWorkbook(string filepath)
        {
            //Initialize a new Workboook object
            Workbook workbook = new Workbook();

            //Specific workbook version
            workbook.Version = ExcelVersion.Version2010;

            //Clear all sheets in workbook
            workbook.Worksheets.Clear();

            //Append a new sheet to worksheet and then name it My Sheet
            workbook.Worksheets.Create("My Sheet");

            //Save workbook to disk
            workbook.SaveToFile(filepath);
        }
    }