2016-04-24 76 views
0

我想制作一个按钮,用于将数据从3个文本框传递到Excel表格,但我希望每次都使用同一个表格,只需将数据添加到新的行。每次我想添加一些东西时,它会创建一个新的excel文件。这是我的代码。如何将数据从C#传递到excel现有文件

 Excel.Workbook xlWorkBook; 
     Excel.Worksheet xlWorkSheet; 
     object misValue = System.Reflection.Missing.Value; 

     xlWorkBook = xlApp.Workbooks.Add(misValue); 
     xlWorkSheet = (Excel.Worksheet)xlWorkBook.Worksheets.get_Item(1); 
     xlWorkSheet.Cells[1, 1] = "Book name"; 
     xlWorkSheet.Cells[1, 2] = "Author"; 
     xlWorkSheet.Cells[1, 3] = "Rating"; 

     string curFile = @"g:\Biblioteca.xls"; 

     if (!File.Exists(curFile)) 
     { 
      xlWorkBook.SaveAs("g:\\Biblioteca.xls", Excel.XlFileFormat.xlWorkbookNormal, misValue, misValue, misValue, misValue, Excel.XlSaveAsAccessMode.xlExclusive, misValue, misValue, misValue, misValue, misValue); 
      xlWorkSheet.Cells[++k, 1] = getName; 
      xlWorkSheet.Cells[k, 2] = getAuthor;  
      xlWorkSheet.Cells[k, 3] = getRating; 
      MessageBox.Show("Excel created succesfuly"); 
     } 
     else 
     { 

      Excel.Application excelApp = (Excel.Application)System.Runtime.InteropServices.Marshal.GetActiveObject("Excel.Application"); 
      Excel.Workbook excelWorkbook = excelApp.Workbooks.Open(curFile, 
        0, false, 5, "", "", false, Excel.XlPlatform.xlWindows, "", 
        true, false, 0, true, false, false); 
      xlWorkSheet.Cells[++k, 1] = getName; 
      xlWorkSheet.Cells[k, 2] = getAuthor; 
      xlWorkSheet.Cells[k, 3] = getRating; 
     } 
     xlWorkBook.Close(true, misValue, misValue); 
     xlApp.Quit(); 


    } 

}

+0

你为什么不尝试使用OleDb呢? – Steve

+0

您能详细解说您遇到的问题吗?当你说它创建一个新文件时,你是否说它进入了'if(!File.Exists(curFile))'块?你是否获得了“Excel创建的成功”消息,或者它是否进入了'else'块,但是还创建了一个新文件? – gmiley

+0

看看下面的SO问题,他们可能会为您提供正确的方法来做你想做的事情。这里:http://stackoverflow.com/questions/20142488/how-to-append-data-into-a-excel-sheet-column和在这里:http://stackoverflow.com/questions/21659069/writing-data-到一个现有-Excel的文件在-C-尖锐 – gmiley

回答

0

您没有打开任何现有的文件!

有关打开现有电子表格的示例,请参阅@ gmiley的第二参考资料。您可能需要研究Range以了解如何放置新数据。

相关问题