Finally, the Excel file is imported from the DataGrid. In order to prevent forgetting it, you can easily record it for everyone and yourself.
The main code in Web applications is as follows:
// Set and bind the datagrid2 data source (skip this step because this step is simple)
/** // * Set the format of datagrid2 to text. This solves the problem of "00000123" to "123" after the Excel file is imported. Here, for the sake of simplicity, I set the overall attribute of the DataGrid. You can also set properties for each cell, such as maid [0]. cells [0]. Attributes. Add ("style", "Vnd. ms-excel.numberformat :@");*/
Datagrid2.attributes. Add ("style", "Vnd. ms-excel.numberformat :@");
// Write data in datagrid2 to an Excel file in the form of Liu
Response. Clear ();
Response. Buffer = true;
Response. charset = "gb2312 ";
Response. appendheader ("content-disposition", "attachment?filename=zjxx.xls ");
Response. contentencoding = system. Text. encoding. getencoding ("gb2312"); // set the output stream to simplified Chinese
Response. contenttype = "application/MS-excel"; // set the output file type to an Excel file.
This. enableviewstate = false;
System. Globalization. cultureinfo mycitrad = new system. Globalization. cultureinfo ("ZH-CN", true );
System. Io. stringwriter ostringwriter = new system. Io. stringwriter (mycitrad );
System. Web. UI. htmltextwriter ohtmltextwriter = new system. Web. UI. htmltextwriter (ostringwriter );
This. datagrid2.rendercontrol (ohtmltextwriter );
Response. Write (ostringwriter. tostring ());
Response. End ();
Windows applications are as follows:
// Zjtable has read data from the database.
Excel. applicationclass excelapp;
Excelapp = new excel. applicationclass ();
Excel. Workbook excelbook = excelapp. workbooks. Add (1 );
Excel. worksheet excelsheet = (Excel. worksheet) excelbook. worksheets [1];
Excelapp. Visible = true;
Excelsheet. cells [1, 1] = "name ";
Excelsheet. cells [1, 2] = "gender ";
Excelsheet. cells [1, 3] = "Date of Birth ";
// Set all cells in the Excel file to text
Excelsheet. cells. numberformatlocal = "@";
For (INT I = 0; I <zjtable. Rows. Count; I ++)
...{
// Import data from zjtable to an Excel file
Datarow ROW = zjtable. Rows [I];
For (Int J = 1; j <= 3; j ++)
Excelsheet. cells [I + 2, J] = row [J]. tostring ();
}