I have been looking around checking how to insert/update data into an existing excel spreadsheet into a specific cell. I first came upon this thread :
Insert text in specific cell in Excel c#
Not sure if I read it right but I don't see anything with regards to using a certain excel file. Would I then be using a combination with this kind of code?
http://csharp.net-informations.com/excel/csharp-excel-oledb-update.htm
Sorry if I'm just using links, don't want to clutter this thread with so much code.
I have not gone through the link that you have mentioned in the post. However, if you are looking at writing or updating the value in a particular cell, you can do it using this line of code:
workSheet.Cells[rowIndex, colIndex] = cellValue;
rowIndex
and columnIndex
are the integer values that represent the index of the row and column of the cell in which you are trying to write/update. cellValue
is the value you are trying to write in the cell. This should be a string.
Sample code:
//Create an excel application object
Excel.Application excelAppObj = new Excel.Application();
excelAppObj.DisplayAlerts = false;
//Open the excel work book
Excel.Workbook workBook = excelAppObj.Workbooks.Open(fileName, 0, false, 5, "", "", false, Excel.XlPlatform.xlWindows, "", true, false, 0, false, false);
//Get the first sheet of the selected work book
Excel.Worksheet worksheet = (Excel.Worksheet)workBook.Worksheets.get_Item(1);
//Write 20 in Cell - C3
workSheet.Cells[2, 3] = "20";
//Save work book (.xlsx format)
workBook.SaveAs(fileName, Excel.XlFileFormat.xlOpenXMLWorkbook, null, null, false,
false, Excel.XlSaveAsAccessMode.xlShared, false, false, null, null, null);
//Release resources
试试这个,
worksheet.Cells[rownumber,columnnumber]="value";
在您命名的站点上,还有另一个链接,名为“ 如何使用OLEDB将数据插入Excel” 。
The code in the first link is using Interop
to update an Excel file and the second link is using OleDb
. You shouldn't really mix the two.
The code from the first one should be easy enough to adjust, you can load a specific excel file by using the Workbooks.Open()
method . Changing the line
xlWorkBook = xlApp.Workbooks.Add(misValue);
to
xlWorkBook = xlApp.Workbooks.Open(yourFilename);
Where yourFileName
is a string that contains the full path to the Excel file you wish to open should work for you.
The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.