//保存的Excel public bool SaveExcel(DataGridView girdView, bool isShowExcle) { if (girdView.Rows.Count == 0) //判斷數(shù)據(jù)是否等于0 return false; //創(chuàng)建 Excel 對(duì)象 Excel.Application excel = new Microsoft.Office.Interop.Excel.Application(); excel.Application.Workbooks.Add(true); excel.Visible = isShowExcle; //生成字段名稱(列名) for (int i = 0; i < dataGridView1.ColumnCount - 1; i++) { excel.Cells[1, i + 1] = girdView.Columns[i].HeaderText; } //填充數(shù)據(jù) for (int i = 0; i < girdView.RowCount - 1; i++) { for (int j = 0; j < girdView.ColumnCount; j++) { //判斷類型是否是字符串 if (girdView[j, i].ValueType == typeof(string)) excel.Cells[i + 2, j + 1] = "'" + girdView[j, i].Value.ToString(); else excel.Cells[i + 2, j + 1] = girdView[j, i].Value; } } return true; }完善上一種方式: public static void ExportDataGridViewToExcel(DataGridView dataGridview1) - {
- SaveFileDialog saveFileDialog = new SaveFileDialog();
- saveFileDialog.Filter = "Execl files (*.xls)|*.xls";
- saveFileDialog.FilterIndex = 0;
- saveFileDialog.RestoreDirectory = true;
- saveFileDialog.CreatePrompt = true;
- saveFileDialog.Title = "導(dǎo)出Excel文件到";
-
- saveFileDialog.ShowDialog();
-
- Stream myStream;
- myStream = saveFileDialog.OpenFile();
- StreamWriter sw = new StreamWriter(myStream, System.Text.Encoding.GetEncoding("gb2312"));
- string str = "";
- try
- {
-
- for (int i = 0; i < dataGridview1.ColumnCount; i++)
- {
- if (i > 0)
- {
- str += "/t";
- }
- str += dataGridview1.Columns[i].HeaderText;
- }
-
- sw.WriteLine(str);
-
- for (int j = 0; j < dataGridview1.Rows.Count; j++)
- {
- string tempStr = "";
- for (int k = 0; k < dataGridview1.Columns.Count; k++)
- {
- if (k > 0)
- {
- tempStr += "/t";
- }
- if (dataGridview1.Rows[j].Cells[k].Value != null)
- {
- tempStr += dataGridview1.Rows[j].Cells[k].Value.ToString();
- }
- }
- sw.WriteLine(tempStr);
- }
- sw.Close();
- myStream.Close();
- }
- catch (Exception e)
- {
- MessageBox.Show(e.ToString());
- }
- finally
- {
- sw.Close();
- myStream.Close();
- }
- }
|