日期:2014-05-20 浏览次数:21014 次
#region 方法【DataGridViewToExcel】:导出excel private void DataGridViewToExcel(DataGridView dgv) { SaveFileDialog saveFileDialog = new SaveFileDialog(); saveFileDialog.Filter = "Execl files (*.xls)|*.xls"; saveFileDialog.FilterIndex = 0; saveFileDialog.RestoreDirectory = true; saveFileDialog.CreatePrompt = true; saveFileDialog.Title = "保存为Excel"; if (saveFileDialog.ShowDialog() == DialogResult.OK) { Stream stream; stream = saveFileDialog.OpenFile(); StreamWriter streamWriter = new StreamWriter(stream, System.Text.Encoding.GetEncoding(-0)); string columnTitle = ""; try { #region 写入列标题 for (int i = 0; i < dgv.ColumnCount; i++) { if (dgv.Columns[i].Visible == true) { if (i > 0) { columnTitle += "\t"; } columnTitle += dgv.Columns[i].HeaderText; } } streamWriter.WriteLine(columnTitle); #endregion #region 写入列内容 for (int j = 0; j < dgv.Rows.Count; j++) { string columnValue = ""; for (int k = 0; k < dgv.Columns.Count; k++) { if (dgv.Columns[k].Visible == true) { if (k > 0) { columnValue += "\t"; } if (dgv.Rows[j].Cells[k].Value == null) { columnValue += ""; } else { columnValue += dgv.Rows[j].Cells[k].Value.ToString(); } } } streamWriter.WriteLine(columnValue); } #endregion streamWriter.Close(); stream.Close(); } catch (Exception ex) { MessageBox.Show(ex.ToString()); } } } #endregion