This article describes the method of saving Sql data into an Excel file in C#, which is very practical. Share it for your reference.
The specific function codes are as follows:
public string ExportExcel( DataSet ds,string saveFileName) { try { if (ds == null) return "The database is empty"; bool fileSaved = false; xlApp = new (); if (xlApp == null) { return "Unable to create Excel object, maybe your machine does not have Excel installed"; } workbooks = ; workbook = (); worksheet = ()[1];//Get sheet1 //Write fields for (int i = 0; i < [0].; i++) { [1, i + 1] = [0].Columns[i].ColumnName; } //Write the value for (int r = 0; r < [0].; r++) { for (int i = 0; i < [0].; i++) { [r + 2, i + 1] = [0].Rows[r][i]; } (); } ();//Column width adaptation. if (saveFileName != "") { try { = true; (saveFileName); fileSaved = true; } catch (Exception ex) { fileSaved = false; ("An error occurred while exporting the file, the file may be being opened!\n" + ); } } else { fileSaved = false; } (); ();//Forcibly destroyed if (fileSaved && (saveFileName)) (saveFileName); //Open EXCEL return "Save to Excel successfully"; } catch (Exception ex) { return (); } }
I hope that the examples described in this article will be helpful to everyone's C# programming.