简体   繁体   English

在C#中从datagridview导出一个excel列

[英]Export one excel column from datagridview in C#

I have excel data as follow:我有excel数据如下:


Project |项目 | person |人 | Time |时间 | Date日期

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

IT |资讯科技 | B |1,20 |2019-10-10 B |1,20 |2019-10-10

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

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

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

IT |资讯科技 | B |乙 | 1.20 |2019-10-12 1.20 |2019-10-12


In my code I can export all excel data from datagridview, how I do to export one column only.在我的代码中,我可以从 datagridview 导出所有 excel 数据,我如何只导出一列。 I want to export column Project and do sort for every type of project and sum eg the exported new excel file should be as follow:我想导出列 Project 并对每种类型的项目进行排序并求和,例如导出的新 Excel 文件应如下所示:

2019-10-10 to 2019-10-12 2019-10-10 至 2019-10-12

Project |项目 | Sum

support |支持 | 1.40 1.40

IT |资讯科技 | 2.40 2.40

debugg |调试 | 30 30

Here is my export code.这是我的导出代码。 can you help me please.你能帮我吗。

Thank you for hand.谢谢你的手。

 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);
    }

For the way you did it you could use something like go through your columns, check which one is selected and then export it, or directly select your column.对于您这样做的方式,您可以使用诸如浏览您的列,检查选择了哪个然后导出它,或直接选择您的列之类的方法。 But there is still room for improvement, I just wrote down what came to my mind.但是还有改进的余地,我只是把我想到的写下来。

 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());

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM