• 用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 
  • 相关阅读:
    noip2017逛公园
    [noip模拟赛]小U的女装
    AT2364 Colorful Balls
    关于bitset
    [ZJOI2010]排列计数
    [noip模拟赛]午餐
    [noip2017]列队
    [学习笔记]dsu on a tree(如何远离线段树合并)
    luogu4917天守阁的地板
    线性求素数+莫比乌斯函数+欧拉函数模板
  • 原文地址:https://www.cnblogs.com/angleSJW/p/1628397.html
Copyright © 2020-2023  润新知