Warning: file_get_contents(/data/phpspider/zhask/data//catemap/5/excel/27.json): failed to open stream: No such file or directory in /data/phpspider/zhask/libs/function.php on line 167

Warning: Invalid argument supplied for foreach() in /data/phpspider/zhask/libs/tag.function.php on line 1116

Notice: Undefined index: in /data/phpspider/zhask/libs/function.php on line 180

Warning: array_chunk() expects parameter 1 to be array, null given in /data/phpspider/zhask/libs/function.php on line 181
C# 使用C将数据追加到现有Excel文件#_C#_Excel_Datagridview_Append_Interop - Fatal编程技术网

C# 使用C将数据追加到现有Excel文件#

C# 使用C将数据追加到现有Excel文件#,c#,excel,datagridview,append,interop,C#,Excel,Datagridview,Append,Interop,我是C#方面的新手,我正在尝试将一些数据从C#中的DataGridView导出到Excel文件中。来自datagridview的输入由用户填写 目前,我的程序可以创建一个excel文件以及datagridview中的值,文件名为给定日期 我的问题是,我似乎找不到从gridview追加数据的方法。如果excel文件已经存在,它会覆盖当前的excel文件 非常感谢您的任何帮助/提示/建议 谢谢:) 这是我的密码: Microsoft.Office.Interop.Excel.Application

我是C#方面的新手,我正在尝试将一些数据从C#中的DataGridView导出到Excel文件中。来自datagridview的输入由用户填写

目前,我的程序可以创建一个excel文件以及datagridview中的值,文件名为给定日期

我的问题是,我似乎找不到从gridview追加数据的方法。如果excel文件已经存在,它会覆盖当前的excel文件

非常感谢您的任何帮助/提示/建议

谢谢:)

这是我的密码:

Microsoft.Office.Interop.Excel.Application xlApp;          
Microsoft.Office.Interop.Excel.Workbook xlWorkBook; 
Microsoft.Office.Interop.Excel.Worksheet xlWorkSheet;
Microsoft.Office.Interop.Excel.Sheets xlBigSheet;
Microsoft.Office.Interop.Excel.Sheets xlSheet;
object misValue;
String newPath;

private void buttonOK_Click(object sender, EventArgs e)
{
    createXLSfile();
}

private void createXLSfile(){
    String cDate = datePicker.Value.ToShortDateString();
    String cMonth = datePicker.Value.ToString("MMMM");
    String cYear = datePicker.Value.ToString("yy");
    String cDay = datePicker.Value.ToString("dd");

    String fName = cDay + "-" + cMonth+ "-" + cYear + ".xls";

    String mainPath = @"C:\Users\User1\Desktop\" + cYear;
    String folderPath = System.IO.Path.Combine(mainPath, cMonth);
    String excelPath = System.IO.Path.Combine(folderPath, fName);

    System.IO.Directory.CreateDirectory(mainPath);
    System.IO.Directory.CreateDirectory(folderPath);

    String fNameOnly = Path.GetFileNameWithoutExtension(excelPath);
    String extension = Path.GetExtension(excelPath);
    String path = Path.GetDirectoryName(excelPath);
    newPath = excelPath;

    if(File.Exists(newPath))
    {
        existingFile();
    }else
    {
        newFile();
    }
    MessageBox.Show("Submitted");
}

private void newFile()
{
    xlApp = new Microsoft.Office.Interop.Excel.Application();
    xlApp.Visible = true;
    misValue = System.Reflection.Missing.Value;
    xlWorkBook = xlApp.Workbooks.Add(misValue);
    xlWorkSheet = (Microsoft.Office.Interop.Excel.Worksheet)xlWorkBook.Worksheets.get_Item(1);

    xlWorkSheet = xlWorkBook.Sheets["Sheet1"];
    xlWorkSheet = xlWorkBook.ActiveSheet;
    xlWorkSheet.Name = "Sheet1";

    xlWorkSheet.Cells[2, 1] = "Header1";
    xlWorkSheet.Cells[2, 2] = "Header2";
    xlWorkSheet.Cells[2, 3] = "Total";
    getData();

    xlWorkBook.SaveAs(newFullPath, Microsoft.Office.Interop.Excel.XlFileFormat.xlWorkbookNormal, misValue,
    misValue, misValue, misValue, Microsoft.Office.Interop.Excel.XlSaveAsAccessMode.xlExclusive, misValue, misValue, misValue, misValue, misValue);
    xlWorkBook.Close(true, misValue, misValue);
    xlApp.Quit();
    Marshal.ReleaseComObject(xlWorkSheet);
    Marshal.ReleaseComObject(xlWorkBook);
    Marshal.ReleaseComObject(xlApp);
}

private void existingFile()
{
    xlApp = new Microsoft.Office.Interop.Excel.Application();
    xlApp.Visible = true;
    xlWorkBook = xlApp.Workbooks.Open(newPath, 0, 
                false, 5, "", "", false, Microsoft.Office.Interop.Excel.XlPlatform.xlWindows,
                 "", true, false, 0, true, false, false);

    xlBigSheet = xlWorkBook.Worksheets;
    string x = "Sheet1";
    xlWorkSheet = (Microsoft.Office.Interop.Excel.Worksheet)xlBigSheet.get_Item(x);

    getData();

    xlWorkBook.SaveAs(newPath, Microsoft.Office.Interop.Excel.XlFileFormat.xlWorkbookNormal,
            misValue, misValue, misValue, misValue, Microsoft.Office.Interop.Excel.XlSaveAsAccessMode.xlExclusive,
            misValue, misValue, misValue,
            misValue, misValue);

    xlWorkBook.Close(misValue, misValue, misValue);
    xlWorkBook = null;
    xlApp.Quit();
    GC.WaitForPendingFinalizers();
    GC.Collect();
    GC.WaitForPendingFinalizers();
    GC.Collect();
}

private void getData()
{
    double a,b,c,d,total = 0;
    int lastRow_ = 3;

    foreach(DataGridViewRow r in dataGridView1.Rows)
    {
        if(!r.IsNewRow)
        {
            a = Convert.ToDouble(r.Cells[2].Value);
            b = Convert.ToDouble(r.Cells[3].Value);
            c = Convert.ToDouble(r.Cells[4].Value);
            d = Convert.ToDouble(r.Cells[5].Value);

            total = a + b + c + d;

            xlWorkSheet.Cells[lastRow_, 1] = "Hi";
            xlWorkSheet.Cells[lastRow_, 2] = "Hello";
            xlWorkSheet.Cells[lastRow_, 3] = Convert.ToString(total);
            lastRow_ = xlWorkSheet.Cells.Find(
                        "*",
                        xlWorkSheet.Cells[1, 1],
                        misValue,
                        Microsoft.Office.Interop.Excel.XlLookAt.xlPart,
                        Microsoft.Office.Interop.Excel.XlSearchOrder.xlByRows,
                        Microsoft.Office.Interop.Excel.XlSearchDirection.xlPrevious,
                        misValue,
                        misValue,
                        misValue).Row + 1;
        }
    }
    total = 0;
}
更新1: 还是卡住了。 我一直在尝试跟踪此链接:

输出


当您需要将数据附加到现有工作表时,您需要找出最后使用的行的位置,并开始在此行之后添加数据。您当前获取此“最后”行的代码很难处理,因为一旦开始添加行,您就会不断检查此“最后”行,这是不必要的。
getData()
方法只是将数据添加到一个新的excel文件中,其中最后一行无关紧要。如果文件存在,则只需获取最后使用的行并开始导入下一行的数据。我猜,随着代码的运行,发送
GetData(RowToStart)
方法的起始行索引,然后简单地增加
lastRow\uuu
变量可能会更好,如下所示:不需要一直检查最后一行

private void getData(int lastRow_) {
  double a, b, c, d, total = 0;
  //int lastRow_ = 4;

  foreach (DataGridViewRow r in dataGridView1.Rows) {
    //if (!row.IsNewRow) {
    if (!r.IsNewRow) {
        a = Convert.ToDouble(r.Cells[2].Value);
      b = Convert.ToDouble(r.Cells[3].Value);
      c = Convert.ToDouble(r.Cells[4].Value);
      d = Convert.ToDouble(r.Cells[5].Value);

      total = a + b + c + d;

      xlWorkSheet.Cells[lastRow_, 1] = "Hi";
      xlWorkSheet.Cells[lastRow_, 2] = "Hello";
      xlWorkSheet.Cells[lastRow_, 3] = Convert.ToString(total);
      lastRow_++;
      //lastRow_ = xlWorkSheet.Cells.Find(
      //            "*",
      //            xlWorkSheet.Cells[1, 1],
      //            misValue,
      //            Microsoft.Office.Interop.Excel.XlLookAt.xlPart,
      //            Microsoft.Office.Interop.Excel.XlSearchOrder.xlByRows,
      //            Microsoft.Office.Interop.Excel.XlSearchDirection.xlPrevious,
      //            misValue,
      //            misValue,
      //            misValue).Row + 1;
    }
  }
  total = 0;
}
如果文件是新的,您可以像下面那样调用此方法

 .
 .
 .
  xlWorkSheet.Cells[3, 1] = "Header1";
  xlWorkSheet.Cells[3, 2] = "Header2";
  xlWorkSheet.Cells[3, 3] = "Total";
  getData(4);
 .
 .
 .
 .
 .
 .

 xlWorkSheet = (Microsoft.Office.Interop.Excel.Worksheet)xlBigSheet.get_Item("Sheet1");
 Microsoft.Office.Interop.Excel.Range last = xlWorkSheet.Cells.SpecialCells(Microsoft.Office.Interop.Excel.XlCellType.xlCellTypeLastCell, Type.Missing);
 int lastUsedRow = last.Row;
 getData(lastUsedRow + 1);
 .
 .
 .
如果文件已经存在,并且需要将数据附加到现有工作表中,则需要获取最后使用的行,然后从下一行开始。您可以调用
getData(RowToStart)
如下所示

 .
 .
 .
  xlWorkSheet.Cells[3, 1] = "Header1";
  xlWorkSheet.Cells[3, 2] = "Header2";
  xlWorkSheet.Cells[3, 3] = "Total";
  getData(4);
 .
 .
 .
 .
 .
 .

 xlWorkSheet = (Microsoft.Office.Interop.Excel.Worksheet)xlBigSheet.get_Item("Sheet1");
 Microsoft.Office.Interop.Excel.Range last = xlWorkSheet.Cells.SpecialCells(Microsoft.Office.Interop.Excel.XlCellType.xlCellTypeLastCell, Type.Missing);
 int lastUsedRow = last.Row;
 getData(lastUsedRow + 1);
 .
 .
 .

我希望这是有意义的。

您当前发布的代码中有一些东西无法编译,因此我对您是否能够将
DataGridView
导出到新的excel文件表示怀疑。行:
String mainPath=“@C:\Users\User1\Desktop\”“+cYear;”
不正确,“@”不正确,末尾有一个额外的“”…应该是
String mainPath=@“C:\Users\User1\Desktop\”+cYear;
行:
System.IO.Directory.Create(folderPath);
不正确,因为
Create
DNE…应该是:
System.IO.Directory.CreateDirectory(mainPath);
最后一个帮助。在调试excel文件的创建时,您可能需要添加以下行:
xlApp.Visible=true;
。这将允许您逐步查看代码中发生的情况,并可能会暴露出您遇到的一些问题。请想一想。@JohnG感谢您的帮助,这只是我自创建excel以来在这里创建的模拟代码主程序太大了。我的目录没有问题,我已经按照你说的做了。它会覆盖excel文件,而不是将其附加到文件中。你对此有什么建议吗?@JohnG我已经清理了问题中的代码。谢谢你指出它。请告诉我我是否正确。因为你的主程序代码太大,所以我无法修改发布…然后是您遇到问题的部分…而不是复制/粘贴您重新键入的代码来创建一个有错误的“模拟”版本?因此,我前面指出的错误实际上并不存在于您的代码中?如果是这样,那么您为什么要浪费其他人的时间?发布代码(不是“模拟”版本)这不起作用。否则,对于您发布的“模拟”代码,答案是…它有错误,但不起作用,因为它是“模拟”代码,其他人尝试调试它或帮助您查找错误是没有意义的。天哪。非常感谢您,它起作用了。谢谢您也容忍我:)最后一个问题抱歉..您知道如何制作“模拟”代码吗文件名。。。。此位置中已存在。是否要替换它?“来自Excel”不显示?谢谢如果不想看到覆盖对话框,可以在Excel中关闭
DisplayAlerts
,如:
xlApp.DisplayAlerts=false;