C# Export Datagrid to Excel File

1801 단어
public void export_datagridview_to_excel(DataGridView dgv, string excel_file)
       { int cols; //open file  StreamWriter wr = new StreamWriter(excel_file);
  //determine the number of columns and write columns to file  cols = dgv.Columns.Count; for (int i = 0; i < cols; i++)
           {
               wr.Write(dgv.Columns[i].DataPropertyName.ToString().ToUpper() + "\t");
           }
 
           wr.WriteLine();
  //write rows to excel file  for (int i = 0; i < (dgv.Rows.Count - 1); i++)
           { for (int j = 0; j < cols; j++)
               { if (dgv.Rows[i].Cells[j].Value != null)
                       wr.Write(dgv.Rows[i].Cells[j].Value + "\t"); else {
                       wr.Write("\t");
                   }
               }
 
               wr.WriteLine();
           }
  //close file  wr.Close();
       }
  private void button2_Click(object sender, EventArgs e)
       {
           export_datagridview_to_excel(dataGridView1, " testexport.xls");
           MessageBox.Show("", "", MessageBoxButtons.OK, MessageBoxIcon.Information);
       }

좋은 웹페이지 즐겨찾기