2 xy596356456 xy596356456 于 2015.05.30 22:59 提问

从datagrid导出数据到excel中出现错误
 private void button2_Click(object sender, EventArgs e)
        {
            SaveFileDialog saveFileDialog = new SaveFileDialog();
            saveFileDialog.Filter = "Excel files (*.xls)|*.xls";
            saveFileDialog.FilterIndex = 0;
            saveFileDialog.RestoreDirectory = true;
            saveFileDialog.CreatePrompt = true;
            saveFileDialog.Title = "导出Excel文件到";

            saveFileDialog.ShowDialog();
            try
            {
                Stream myStream;
                myStream = saveFileDialog.OpenFile();
                StreamWriter sw = new StreamWriter(myStream, System.Text.Encoding.GetEncoding("utf-8"));
                string str = "";

                //写标题  
                for (int i = 0; i < grid1.ColumnCount; i++)
                {
                    if (i > 0)
                    {
                        str += "\t";
                    }
                    str += grid1.Columns[i].HeaderText;
                }

                sw.WriteLine(str);
                //写内容 
                for (int j = 0; j < grid1.Rows.Count; j++)
                {
                    string tempStr = "";
                    for (int k = 0; k < grid1.Columns.Count; k++)
                    {
                        if (k > 0)
                        {
                            tempStr += "\t";
                        }
                        tempStr += grid1.Rows[j].Cells[k].Value.ToString();
                    }
                    sw.WriteLine(tempStr);
                }
                MessageBox.Show("导出成功", "提示", MessageBoxButtons.OK, MessageBoxIcon.Information);
                sw.Close();
                myStream.Close();
            }
            catch (Exception)
            {
                //MessageBox.Show(ex.ToString());
            }
            finally
            {
                //sw.Close();
                //myStream.Close();
            }
        }

如上 ColumnCount 、Rows、Columns等在 "System.Windows.From.DataGrid"不包含"

4个回答

devmiao
devmiao   Ds   Rxr 2015.05.30 23:01
已采纳

winforms是datagridview,asp.net才是datagrid

xy596356456
xy596356456 突然间惊醒了我.................
2 年多之前 回复
guwei4037
guwei4037   Ds   Rxr 2015.05.30 23:01
edouardzyc
edouardzyc   2015.05.31 09:16

也可以试试openxml

xy596356456
xy596356456   2015.06.01 14:23

谢谢大家的帮助 问题解决了 我的控件的确不对

Csdn user default icon
上传中...
上传图片
插入图片