2
我不知道爲什麼我很難找到這個簡單任務的例子,但是根據我的Google-Fu技能沒有顯示任何內容。我正在尋找使用OpenXML和VB.Net修改現有電子表格的單元格的示例。在VB.Net中使用OpenXML修改單元格
我想將現有值更改爲新值,不涉及公式。
以下是我有:
Public Sub Main()
Dim strSource, strSheetName As String
Dim dtPeriod As DateTime
strSource = Dts.Variables("sFilePath").Value
'set period to previous month. We only care about the year in this period as the data will be reloaded
'from the file each month
dtPeriod = DateAdd(DateInterval.Month, -1, Today)
Dts.Variables("dtPeriod").Value = dtPeriod
Using mySpreadSheet As SpreadsheetDocument = SpreadsheetDocument.Open(strSource, True)
Dim WorkbookSheets As Sheets
WorkbookSheets = mySpreadSheet.WorkbookPart.Workbook.GetFirstChild(Of Sheets)()
For Each childSheet As Sheet In WorkbookSheets
strSheetName = childSheet.Name
strSheetName = strSheetName.ToLower.Trim
If strSheetName = "sheet1" Then 'process sheet
SetCellValue("A1", "Last Name")
SetCellValue("B1", "First Name")
SetCellValue("C1", "RegionID")
SetCellValue("D1", "RegionName")
'rename sheet for loading
childSheet.Name = "RegionData"
End If
Next
mySpreadSheet.WorkbookPart.Workbook.Save()
mySpreadSheet.Close()
End Using
End Sub
Private Sub SetCellValue(ByVal loc As String, ByVal Val As String)
Dim cell As Cell = New Cell
cell.CellReference = loc
cell.DataType = CellValues.String
cell.CellValue = New CellValue(Val)
End Sub
我敢肯定,這是一些簡單的像確保電池被引用正確表,但我發現所有的例子是創建一個新的工作表。
感謝
那麼這是什麼代碼在做什麼?它沒有做什麼?這裏在黑暗中拍攝,但在Excel中,範圍將爲** sheet1 **,而工作表本身爲** sheet1 $ **另外,您需要注意區分大小寫。同樣,默認值爲Sheet1 $ – billinkc
代碼沒有更新單元格值。我試圖在不使用Excel的情況下修改Excel文件,因爲它必須在服務器上運行。使用Excel作爲客戶端應用程序,我必須找到其他方式來完成它,因此OpenXML。我無法讓OpenXML更新單元格/列值。 – user1238918
Gotcha。運行檢查表名稱,它可能會錯過後面的$和有錯誤的情況? – billinkc