C # method and code for generating an Excel file
Example:
Class AppTest
{
Private Excel. ApplicationClass _ x;
Public static void Main0 ()
{
AppTest a = new AppTest ();
A. _ x = new Excel. ApplicationClass ();
A. _ x. UserControl = false;
For (int I = 0; I <4; I ++)
{
A. SaveToXls ("D: // test //" + I + ". xls"); // In this example, the test folder created on disk D is used.
}
A. _ x. Quit ();
System. Runtime. InteropServices. Marshal. ReleaseComObject (object) a. _ x );
System. GC. Collect ();
}
Private void SaveToXls (string filename)
{
Excel. WorkbookClass wb = (Excel. WorkbookClass) this. _ x. Workbooks. Add (System. Reflection. Missing. Value );
For (int I = 1; I <= 4; I ++)
{
This. _ x. Cells [I, 1] = I. ToString ();
This. _ x. Cells [I, 2] = "'bbb2 ";
This. _ x. Cells [I, 3] = "'ccc3 ";
This. _ x. Cells [I, 4] = "'aaa4 ";
}
Wb. Saved = true;
This. _ x. ActiveWorkbook. SaveCopyAs (filename );
}
}
[Note: You need to add the Excel. dll component to run VS. Net. The Excel component VS. Net itself does not exist. The following describes how to generate Excel. dll .]
1. Make sure that the machine itself needs to install OFFICE.
2. copy the EXCEL9.OLB file under [C:/Program Files/Microsoft Office/Office: default installation path] to [C:/Visual Studio. net/SDK/v1.1/Bin:.. Net installation path.
3. open Visual Studio. run TlbImp Excel9.olb Excel. dll in [C:/Visual Studio.. Net/SDK/v1.1/Bin. dll component.
4. Add an Excel. dll reference to the project.