2017-01-13 65 views
1

在下面的代碼中,將多個附加clde添加到cconvert excel文件並將多個圖紙添加到Tsv文件中。如何將具有多個工作表的Excel文件轉換爲一組TSV文件?

注:下面的代碼轉換爲Excel用一張紙來Tsv.It文件不處理與多張Excel表

Public Sub Main() 

     Dim oExcel As Object 
     Dim oBook As Object 

     Dim sFileName As String 
     Dim sFileNameOnly As String 


     Dim sXlsPath As String 
     Dim sTsvPath As String 



     sFileName = CStr(Dts.Variables("User::Xls_File_Name").Value) 


     sXlsPath = "H:\Xls_Files\" + sFileName 

     sFileNameOnly = Path.GetFileNameWithoutExtension(sFileName) 

     sTsvPath = "H:\Xls_Files\" + sFileNameOnly + ".Txt" 


     oExcel = CreateObject("Excel.Application") 


     oBook = oExcel.Workbooks.Open(sXlsPath) 

     oBook.SaveAs(sTsvPath, -4158) 

     oBook.Close(False) 
    enter code here 
     oExcel.Quit() 

     Dts.TaskResult = ScriptResults.Success 
    End Sub 
+0

一種可能性是創建臨時工作簿時,[各表複製到它](http://stackoverflow.com/questions/14734578/ c-sharp-excel-save-each-worksheet-to-a-new-workbook),把它保存到'tsv'中,然後一旦完成,丟棄它而不保存。 – stuartd

回答

1

您可以使用Microsoft.Office.Interop.Excel該任務(注意,你需要引用該名稱空間首先)。

爲@stuartd建議你可以創建一個彙總表,將根據你的表結構包含所有的表(請參閱裏面的代碼我的意見) 或替代地(如果它適合你的需要),您可以在保存每個工作表一個使用For Each循環的不同的tsv文件。
這裏是一個測試例示出的,該原則:

Imports Microsoft.Office.Interop 
Imports Microsoft.Office.Interop.Excel 

    Public Sub Main() 
      Dim xlApp As New Excel.Application 
      Dim xlWorkBook As Excel.Workbook 
      Dim xlWorkSheet As Excel.Worksheet 
      xlApp.Visible = False 

      ' create a new workbook (you can open existing workbooks using the Open() method) ' 
      xlWorkBook = xlApp.Workbooks.Add() 
      ' create sheet 1 ' 
      xlWorkSheet = xlWorkBook.Worksheets.Add() 
      xlWorkSheet.Name = "ws1" 
      xlWorkSheet.Range("a1").Value = "hello from worksheet1" 
      ' create sheet 2 ' 
      xlWorkSheet = xlWorkBook.Worksheets.Add() 
      xlWorkSheet.Name = "ws2" 
      xlWorkSheet.Range("a1").Value = "hello from worksheet2" 
      ' worksheet that contain both worksheets ' 
      xlWorkSheet = xlWorkBook.Worksheets.Add() 
      xlWorkSheet.Name = "summary" 

      ' paste all sheets data inside the summary sheets (i dont know how your excel sheets are structured but you can select entire ranges and arrange them on the summary worksheet) ' 
      Dim counter As Int16 = 1 
      For Each w As Worksheet In xlWorkBook.Worksheets 
       If w.Name <> "summary" Then 
        xlWorkSheet.Cells(counter, 1) = w.Range("a1") 
        counter += 1 
       End If 
      Next 
      xlApp.DisplayAlerts = False 
      ' save as tsv file ' 
      xlWorkBook.SaveAs("c:\xxx\xxx\Book4.tsv", XlFileFormat.xlTextWindows, CreateBackup:=False) 
     End Sub 
+0

非常感謝。因此,代碼需要在執行代碼之前預計所有工作表的名稱? – user1254579

+0

我在SSIS(腳本任務)中使用Micrsoft Visual Basic 2012。當我使用下面的導入時,它顯示名稱空間在導入時導入Microsoft.Office.Interop 導入Microsoft.Office.Interop.Excel不包含任何公共memebr – user1254579

+0

從* com部分引用內部引用添加?換句話說,你是這麼做的:右鍵單擊項目>>添加引用>>單擊COM >>檢查Microsoft Excel x.0對象庫>>確定? – jonathana

相關問題