zoukankan      html  css  js  c++  java
  • winfrom gridview 导出到Excel文件的代码

    SaveFileDialog saveFileDialog = new SaveFileDialog();
    saveFileDialog.Filter = "Execl files (*.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 < dataGridView1.ColumnCount; i++)
    {
    if (i > 0)
    {
    str += "\t";
    }
    str += dataGridView1.Columns[i].HeaderText;
    }

    sw.WriteLine(str);
    //写内容
    for (int j = 0; j < dataGridView1.Rows.Count-1; 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 ex)
    {
    MessageBox.Show(ex.ToString());
    }
    finally
    {
    sw.Close();
    myStream.Close();
    }

  • 相关阅读:
    字符串方法
    函数的属性和方法
    数组的去重!!
    常见的数组方法
    JS中的函数
    JavaScript 中表达式和语句的区别
    运算符优先级
    题解 CF813B 【The Golden Age】
    题解 CF834B 【The Festive Evening】
    题解 CF810B 【Summer sell-off】
  • 原文地址:https://www.cnblogs.com/happychen/p/5056863.html
Copyright © 2011-2022 走看看