在窗体中把DataGridView中的数据导出Excel

2021-07-15 15:21

阅读:350

标签:day   oid   filter   filename   sof   lte   name   dex   director   

        //DataGridView导出Excel
        private void bt_Excl_Click(object sender, EventArgs e)
        {
            SaveFileDialog saveFileDialog = new SaveFileDialog();

            saveFileDialog.Filter = "Microsoft Excel 工作表 (.xls)|*.xls";
            saveFileDialog.FilterIndex = 0;
            saveFileDialog.RestoreDirectory = true;
            saveFileDialog.CreatePrompt = true;
            saveFileDialog.Title = "导出Excel文件到";
            DateTime now = DateTime.Now;
            saveFileDialog.FileName = now.Year.ToString().PadLeft(2) + now.Month.ToString().PadLeft(2, ‘0‘) + now.Day.ToString().PadLeft(2, ‘0‘) + "-" + now.Hour.ToString().PadLeft(2, ‘0‘) + now.Minute.ToString().PadLeft(2, ‘0‘) + now.Second.ToString().PadLeft(2, ‘0‘);
            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                 {
                    if (i > 0)
                    {
                        str += "\t";
                    }
                    str += dataTitl.Columns[i].HeaderText;
                }
                sw.WriteLine(str);
                //写内容
                for (int j = 0; j                 {
                    string tempStr = "";
                    for (int k = 0; k                     {
                        if (k > 0)
                        {
                            tempStr += "\t";
                        }
                        tempStr += dataTitl.Rows[j].Cells[k].Value.ToString();
                    }
                    sw.WriteLine(tempStr);
                }
                sw.Close();
                myStream.Close();
            }
            catch (Exception)
            {
                MessageBox.Show("题目导出完成。", "导出", MessageBoxButtons.OK, MessageBoxIcon.Asterisk);
            }
            finally
            {
                sw.Close();
                myStream.Close();
            }
        }

在窗体中把DataGridView中的数据导出Excel

标签:day   oid   filter   filename   sof   lte   name   dex   director   

原文地址:https://www.cnblogs.com/Mo-Maek/p/8932391.html


评论


亲,登录后才可以留言!