zoukankan      html  css  js  c++  java
  • Winform中datagridview导出Excel

    using System;
    using System.Collections.Generic;
    using System.ComponentModel;
    using System.Data;
    using System.Drawing;
    using System.Text;
    using System.Windows.Forms;
    using System.IO;
    using System.Data.SqlClient;

    namespace ExportExcel
    {
        public partial class Form1 : Form
        {
            public Form1()
            {
                InitializeComponent();
            }

            private void btnExcel_Click(object sender, EventArgs e)
            {
                SaveAs();
            }
            private void SaveAs() //另存新档按钮   导出成Excel
            {    
                SaveFileDialog saveFileDialog = new SaveFileDialog();
                saveFileDialog.Filter = "Execl files (*.xls)|*.xls";
                saveFileDialog.FilterIndex = 0;
                saveFileDialog.RestoreDirectory = true;
                saveFileDialog.CreatePrompt = true;
                saveFileDialog.Title = "Export Excel File To";
                DialogResult result =  saveFileDialog.ShowDialog();
                Stream myStream;
                if (result == DialogResult.Cancel)
                {
                    return;
                }
                else
                {
                    myStream = saveFileDialog.OpenFile();
                }
               
                StreamWriter sw = new StreamWriter(myStream, System.Text.Encoding.GetEncoding(-0));
                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";
                            }
                            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();
                }
            }

            private void Form1_Load(object sender, EventArgs e)
            {
                string sql = "select * from [user]";
                SqlConnection con = new SqlConnection(@"Data Source=.\sqlexpress;Initial Catalog=Test;Integrated Security=True");
                SqlCommand com = new SqlCommand(sql,con);
                DataSet ds = new DataSet();
                SqlDataAdapter sda = new SqlDataAdapter();
                sda.SelectCommand = com;
                sda.Fill(ds);
                this.dataGridView1.DataSource = ds.Tables[0];

    this.dataGridView1.AllowUserToAddRows = false;//不允许用户添加行,如果设置为true,遍历DataGridView时会把最后一条允许用户添加的行算进去,容易导致空指针异常
                con.Close();
            }
        }
    }

  • 相关阅读:
    Which is best in Python: urllib2, PycURL or mechanize?
    Ruby开源项目介绍(1):octopress——像黑客一样写博客
    Truncated incorrect DOUBLE value解决办法
    Qt Quarterly
    Rich Client Platform教程
    iOS6 中如何获得通讯录访问权限
    省赛热身赛之Javabeans
    [置顶] [开心学php100天]第三天:不羁的PHP文件操作
    hdu2033 人见人爱A+B
    [置顶] AAM算法简介
  • 原文地址:https://www.cnblogs.com/tianguook/p/1732867.html
Copyright © 2011-2022 走看看