2016-02-01 74 views
0

我一直在爲一個小項目努力工作,但它應該很容易。我在vba中有一個windows窗體應用程序來將值插入到excel文件中。 它曾經在我公司工作,因爲我們只有一對「數據」輸入。但現在我們使用txt文件來收集數據,將它們插入到excel文件中。Vb.net將txt.file插入到模板Excel中

我的問題是我們不能再使用宏,因爲總會有人在代碼中改變某些東西。

我的代碼是這樣的:

Dim oApp As Excel.Application 
    Try 
     oApp = DirectCast(CreateObject("Excel.Application"), Excel.Application) 
     oApp.Workbooks.OpenText(Filename:=TextBox1.Text, _ 
           Origin:=Excel.XlPlatform.xlMSDOS, _ 
           DataType:=Excel.XlTextParsingType.xlDelimited, _ 
           Comma:=False, Semicolon:=True, _ 
           StartRow:=1) 
     oApp.Visible = True 
     oApp.Workbooks.Item(TextBox4.Text).SaveAs(Filename:=TextBox2.Text, _ 
               FileFormat:=Excel.XlFileFormat.xlWorkbookNormal) 

     oApp.Workbooks.Item(TextBox3.Text).Close(SaveChanges:=False) 
     'Quit Excel 
     oApp.Quit() 
     oApp = Nothing 
     MessageBox.Show("Success.", "Success!", MessageBoxButtons.OK) 
    Catch ex As Exception 
     MessageBox.Show(ex.Message.ToString, "Error", MessageBoxButtons.OK) 
    End Try 

現在我想用一個模板Excel,並在Sheet1中插入數據,原因Sheet2中擁有所有圖表和東西..

Private Sub Button2_Click(ByVal sender As System.Object, ByVal e As System.EventArgs) Handles Button2.Click 

    xlWorkBook = xlApp.Workbooks.Open(TextBox2.Text) 
    xlApp.Visible = True 
    xlWorkSheet = xlWorkBook.Sheets("data") 

    **With xlWorkSheet 
     '~~> Directly type the values that we want 
     .Range("A1").Value = "1" 
     .Range("A2").Value = "2" 
    End With** 
End Sub 

,我不知道如何實現。我不知道如何把txt文件和「放置」在sheet1中.. 謝謝大家!

+0

通常的語法是xlworksheet.rows(1).cells(1).value =「1」 – Nefariis

+0

我沒有得到。你能解釋嗎?因爲我可以預測它只增加值1 .. – noidea

+0

重點不在於使用「範圍」...使用.rows(rownum).cells(columnnum).value ...該索引不是0基於所以「A1 「將是.rows(1).cells(1)...你是否真的想把文本文件放入excel中?或者把文件讀入excel? – Nefariis

回答

0

將文本文件逐行插入到excel中。

Dim inFile as string() = file.ReadAllLines("yourFileName") 
xlWorkBook = xlApp.Workbooks.Open(TextBox2.Text) 
xlApp.Visible = True 
xlWorkSheet = xlWorkBook.Sheets("data") 

for x as integer = 0 to inFile.length - 1 
    dim splitLine as String() = infile(x).split(";"c) 
    For y as integer = 0 to splitLine.length - 1 
     xlWorkSheet.rows(x + 1).Cells(y + 1).value = splitLine(y) 
    Next 
Next 

如果你只是想將文件附加與展示,然後我會用這個圖標。

xlWorkSheet.Shapes.AddOLEObject("Word.Document.8", "YourfilePath", False, False) 

我相信應該有效。

+0

不錯!它工作完美! offtopic,我在哪裏實現分隔符,分號:= True? cumps – noidea

+0

你使用了哪一個?頂部的代碼或底部的代碼? - 我將假設頂端的代碼...還沒有使用分號分號導入它,你需要使用.split(「;」c) – Nefariis

+0

我使用頂級的!這就是我的想法..但我仍然在管理何時/在哪裏實施拆分方法。 – noidea