简体   繁体   中英

C# - Creating an Excel File in Visual Studio

Is it possible to create an excel spreadsheet in visual studio without opening the Excel Program?

Does the data save in the database of the project?

You can reference the assembly Microsoft.Office.Interop.Excel and generate the Excel file during your program's initialization like so

using Excel = Microsoft.Office.Interop.Excel;

// ... ...

var excel = new Excel.Application();

var workBooks = excel.Workbooks;
var workBook = workBooks.Add();
var workSheet = (Excel.Worksheet)excel.ActiveSheet;

workSheet.Cells[1, "A"] = "Foo";
workSheet.Cells[1, "B"] = "Bar";

// ...
workBook.SaveAs(Directory.GetCurrentDirectory()+"\\"+filename, Excel.XlFileFormat.xlOpenXMLWorkbook);

That is almost as effective as creating an Excel file in VS and adding it to the project's resources.

There's an office open XML SDK that works nicely, to create and modify all MS office file types. That's the best solution, IMHO. But, if you use really old versions of visual studio, they used to have project types that were tightly bound to Excel files. They could add buttons and processing right into the workbook. That functionality might still exist in some downloadable project type.

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM