Loading...

java .net

C# 由DataGridView导出到Excel

private void buttonToExcel_Click(object sender, EventArgs e)
{

    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";
    saveFileDialog.ShowDialog();
    Stream myStream;
    myStream = saveFileDialog.OpenFile();
    StreamWriter sw = new StreamWriter(myStream, System.Text.Encoding.GetEncoding(-0));
    string str = "";
    try
    {
        //写标题
        for (int i = 0; i < this.dataGridView3.ColumnCount; i++)
        {
            if (i > 0)
            {
                str += "\t";
            }

            str += this.dataGridView3.Columns[i].HeaderText;
        }
        sw.WriteLine(str);
        //写内容
        for (int j = 0; j < this.dataGridView3.Rows.Count; j++)
        {
            string tempStr = "";
            for (int k = 0; k < this.dataGridView3.Columns.Count; k++)
            {
                if (k > 0)
                {
                    tempStr += "\t";
                }
                tempStr += this.dataGridView3.Rows[j].Cells[k].Value + "";
            }
            sw.WriteLine(tempStr);
        }

        sw.Close();
        myStream.Close();
    }
    catch (Exception ex)
    {
        MessageBox.Show(ex.ToString());
    }

    finally
    {
        sw.Close();
        myStream.Close();
    }    
    MessageBox.Show("OK");
}

posted on 2009-06-03 12:23 阅读(1134) 评论(0)  编辑  收藏 所属分类: C#


只有注册用户登录后才能发表评论。


网站导航:
 

公告

希望有一天

我能用鼠标双击我的钱包

然后选中一张100元

按住“ctrl+c”

接着不停的“ctrl+v”

嘻嘻~~~笑醒~~~



导航

<2009年6月>
31123456
78910111213
14151617181920
21222324252627
2829301234
567891011

统计

常用链接

留言簿(6)

随笔分类(102)

随笔档案(398)

文章分类

文章档案(10)

有趣网络

搜索

积分与排名

最新评论

阅读排行榜

评论排行榜