• 用stream将dgv中的数据导出到word或excel中小例子


    代码
     1 private void DataGridViewToExcel(DataGridView dgv)
     2         {
     3             SaveFileDialog dlg = new SaveFileDialog();
     4             //dlg.Filter="Word files(*.doc)|*.doc";
     5             dlg.Filter = "Execl files (*.xls)|*.xls";
     6             dlg.FilterIndex = 0;
     7             dlg.RestoreDirectory = true;
     8             dlg.CreatePrompt = true;
     9             dlg.Title = "保存为Excel文件";
    10             if (dlg.ShowDialog() == DialogResult.OK)
    11             {
    12                 Stream myStream;
    13                 myStream = dlg.OpenFile();
    14                 StreamWriter sw = new StreamWriter(myStream, System.Text.Encoding.GetEncoding(-0));
    15                 string columnTitle = "";
    16                 try
    17                 {
    18                     //写入列标题
    19                     for (int i = 0; i < dgv.ColumnCount; i++)
    20                     {
    21                         if (i > 0)
    22                         {
    23                             columnTitle += "\t";
    24                         }
    25                         columnTitle += dgv.Columns[i].HeaderText;
    26                     }
    27                     sw.WriteLine(columnTitle);
    28                     //写入列内容
    29                     for (int j = 0; j < dgv.Rows.Count; j++)
    30                     {
    31                         string columnValue = "";
    32                         for (int k = 0; k < dgv.Columns.Count; k++)
    33                         {
    34                             if (k > 0)
    35                             {
    36                                 columnValue += "\t";
    37                             }
    38                             if (dgv.Rows[j].Cells[k].Value == null)
    39                                 columnValue += "";
    40                             else
    41                                 columnValue += dgv.Rows[j].Cells[k].Value.ToString().Trim();
    42                         }
    43                         sw.WriteLine(columnValue);
    44                     }
    45                     sw.Close();
    46                     myStream.Close();
    47                 }
    48                 catch (Exception e)
    49                 {
    50                     MessageBox.Show(e.ToString());
    51                 }
    52                 finally
    53                 {
    54                     sw.Close();
    55                     myStream.Close();
    56                 }
    57             }
    58         }
    59  代码来源:网络。
    60  
    61 
  • 相关阅读:
    sql中table用法
    sql group by
    C#excel导入
    手写简单JDBC
    连接池+事务
    mysql+jdbc
    mysql(多表)
    jsp标签+jstl
    页面跳转+路径问题
    ajax 动态获取数据库中的值
  • 原文地址:https://www.cnblogs.com/angleSJW/p/1628397.html
Copyright © 2020-2023  润新知