【问题标题】:Export one excel column from datagridview in C#从 C# 中的 datagridview 导出一个 excel 列
【发布时间】:2019-12-06 17:02:48
【问题描述】:

我的excel数据如下:


项目 |人 |时间 |日期

支持 |一个 |50 | 2019-10-10

信息技术 | B |1,20 |2019-10-10

调试 | A |30 |2019-10-11

支持 | c |20 |2019-10-11

支持 | A |30 |2019-10-12

信息技术 |乙| 1.20 |2019-10-12


在我的代码中,我可以从 datagridview 导出所有 excel 数据,如何只导出一列。我想导出列项目并对每种类型的项目进行排序并求和,例如导出的新 excel 文件应如下所示:

2019 年 10 月 10 日至 2019 年 10 月 12 日

项目 |总和

支持 | 1.40

信息技术 | 2.40

调试 | 30

这是我的导出代码。你能帮帮我吗?

谢谢你的帮助。

 private void copyAlltoClipboard()
    {
        dataGridView1.SelectAll();
        DataObject dataObj = dataGridView1.GetClipboardContent();
        if (dataObj != null)
            Clipboard.SetDataObject(dataObj);
    }

    private void Button4_Click(object sender, EventArgs e)
    {
        copyAlltoClipboard();
        Microsoft.Office.Interop.Excel.Application xlexcel;
        Microsoft.Office.Interop.Excel.Workbook xlWorkBook;
        Microsoft.Office.Interop.Excel.Worksheet xlWorkSheet;
        object misValue = System.Reflection.Missing.Value;
        xlexcel = new Excel.Application();
        xlexcel.Visible = true;
        xlWorkBook = xlexcel.Workbooks.Add(misValue);
        xlWorkSheet = (Excel.Worksheet)xlWorkBook.Worksheets.get_Item(1);
        Excel.Range CR = (Excel.Range)xlWorkSheet.Cells[1, 1];
        CR.Select();
        xlWorkSheet.PasteSpecial(CR, Type.Missing, Type.Missing, Type.Missing, Type.Missing, Type.Missing, true);
    }

【问题讨论】:

标签: c# excel export


【解决方案1】:

对于您执行此操作的方式,您可以使用类似浏览您的列,检查选择了哪一个,然后将其导出,或者直接选择您的列。不过还有改进的余地,我只是把想到的写下来。

 StringBuilder strContent = new StringBuilder();
 foreach (DataGridViewColumn col in dgv.Columns)
 {
     if(col.Selected)
     {
         foreach (DataGridViewRow row in dgv.Rows)
         {
            strContent.Append(row.Cells[col.Index].Value.ToString());
            strContent.Append("\t");
        }
     }
  }
  Clipboard.SetText(strContent.ToString());

【讨论】:

  • 谢谢你的回答,我应该把你的代码放在哪里?
  • 要么为仅列选择创建一个新函数,要么在您的 copyAlltoClipboard() 函数中使用它并检查您是否选择了一个或多个/所有列
  • 我在 foreach 行代码“col.Cells”处出错,消息错误显示 datagridview 没有单元格定义
  • 哦,我的错,我编辑了上面的代码。然后你必须遍历行而不是单元格,如果选择多个,这会使其变慢,正如我所说,肯定有一些东西需要改进。
猜你喜欢
  • 1970-01-01
  • 1970-01-01
  • 2016-04-16
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
相关资源
最近更新 更多