C#中导出dataGridView数据为Excel
#region 导出Excel功能函数
private void ExportDataToExcel ( DataGridView dataView, string filePath)
{ try { using ( StreamWriter writer = new StreamWriter ( filePath, false , Encoding. UTF8) ) { for ( int i = 0 ; i < dataView. Columns. Count; i++ ) { writer. Write ( dataView. Columns[ i] . HeaderText) ; if ( i < dataView. Columns. Count - 1 ) { writer. Write ( "," ) ; } } writer. WriteLine ( ) ; foreach ( DataGridViewRow row in dataView. Rows) { if ( ! row. IsNewRow) { for ( int i = 0 ; i < dataView. Columns. Count; i++ ) { writer. Write ( row. Cells[ i] . Value?. ToString ( ) ) ; if ( i < dataView. Columns. Count - 1 ) { writer. Write ( "," ) ; } } writer. WriteLine ( ) ; } } } MessageBox. Show ( "Data exported successfully." , "Success" , MessageBoxButtons. OK, MessageBoxIcon. Information) ; } catch ( Exception ex) { MessageBox. Show ( "Error exporting data: " + ex. Message, "Error" , MessageBoxButtons. OK, MessageBoxIcon. Error) ; }
} #endregion
按键
private void menuExportFile_Click ( object sender, EventArgs e) { using ( SaveFileDialog saveFileDialog = new SaveFileDialog ( ) ) { saveFileDialog. Filter = "Excel files (*.xlsx)|*.xlsx|CSV files (*.csv)|*.csv" ; saveFileDialog. Title = "Save as" ; saveFileDialog. FileName = $" { DateTime. Now : yyyyMMddHHmmss} " ; if ( saveFileDialog. ShowDialog ( ) == DialogResult. OK) { string filePath = saveFileDialog. FileName; string fileExtension = Path. GetExtension ( filePath) . ToLower ( ) ; if ( fileExtension == ".csv" ) { ExportDataToExcel ( dataView, filePath) ; } else if ( fileExtension == ".xlsx" ) { ExportDataToExcel ( dataView, filePath) ; } else { MessageBox. Show ( "Unsupported file format." , "Error" , MessageBoxButtons. OK, MessageBoxIcon. Error) ; } } } }