C# datagridview 导出EXCEL 类

C# datagridview 导出EXCEL 类

datagridview里的数据导出到excel里.网上搜了一下,

有两种方法:

一种用创建一个excel应用程序,模拟操作excel写入单元格.

一种是用流,历遍datagridview的每一行(列与列之间增加一个"\t"),然后写入Stream.保存为一个*.xls文件.

流的方法很快,下面上代码:

class DTE
    {
        public static void dvtoexcle(DataGridView dv, string filename, int isopen)
        {
            if(dv.Rows.Count<=0)
            {
                MessageBox.Show("当前没有可导出记录,请查询后重试!","系统提示:"); return;
            }
            string saveFileName = "";
            SaveFileDialog saveDialog = new SaveFileDialog(); //新建保存对话框
            saveDialog.DefaultExt = "xls";
            saveDialog.Filter = "Excel文件|*.xls";
            saveDialog.FileName = filename;
           
            if(saveDialog.ShowDialog()==DialogResult.OK)
            {
                saveFileName = saveDialog.FileName;
                //MessageBox.Show(saveFileName);
                try
                {
                    Stream st;
                    st = saveDialog.OpenFile();
                    StreamWriter sw = new StreamWriter(st, Encoding.GetEncoding("GB2312"));
                    //第一行列标题
                    string title = "";
                    for (int i = 0; i < dv.ColumnCount; i++)
                    {
                        if(dv.Columns[i].Visible){title += dv.Columns[i].HeaderText + "\t";}
                    }
                    sw.WriteLine(title);
                    //第二行,内容
                    for (int j = 0; j < dv.Rows.Count; j++)
                    {
                        string colvalue = "";
                        for (int k = 0; k < dv.Columns.Count; k++)
                        {
                            if (dv.Columns[k].Visible)
                            {
                                if (dv.Rows[j].Cells[k].Value == null) { colvalue = ""; }
                                else { colvalue += dv.Rows[j].Cells[k].Value.ToString().Trim() + "\t"; }
                            }
                        }
                        sw.WriteLine(colvalue);
                    }
                    sw.Close();
                    st.Close();
                }
                catch (Exception ex) { MessageBox.Show(ex.ToString(),"系统提示:"); }
            }
            if (isopen==1 &&File.Exists(saveFileName)) System.Diagnostics.Process.Start(saveFileName);
        }

你可能感兴趣的:(exception,Stream,String,Excel,C#,Class)