VB.NET - Excel Add-in in VB.Net - How to access the workbook/worksheet?

Asked By Huzefa Motiwalla
06-May-09 06:27 PM
end of post

objExcel.Workbooks and objExcel.Worksheets  objExcel.Workbooks and objExcel.Worksheets

06-May-09 08:55 PM
Private Sub Button1_Click(ByVal sender As System.Object, _
      ByVal e As System.EventArgs) Handles Button1.Click
        Dim objBooks As Excel.Workbooks
        Dim objSheets As Excel.Sheets
        Dim objSheet As Excel._Worksheet
        Dim range As Excel.Range

        ' Create a new instance of Excel and start a new workbook.
        objApp = New Excel.Application()
        objBooks = objApp.Workbooks
        objBook = objBooks.Add
        objSheets = objBook.Worksheets
        objSheet = objSheets(1)

        'Get the range where the starting cell has the address
        'm_sStartingCell and its dimensions are m_iNumRows x m_iNumCols.
        range = objSheet.Range("A1", Reflection.Missing.Value)
        range = range.Resize(5, 5)

        If (Me.FillWithStrings.Checked = False) Then
            'Create an array.
            Dim saRet(5, 5) As Double

            'Fill the array.
            Dim iRow As Long
            Dim iCol As Long
            For iRow = 0 To 5
                For iCol = 0 To 5

                    'Put a counter in the cell.
                    saRet(iRow, iCol) = iRow * iCol
                Next iCol
            Next iRow

            'Set the range value to the array.
            range.Value = saRet

        Else
            'Create an array.
            Dim saRet(5, 5) As String

            'Fill the array.
            Dim iRow As Long
            Dim iCol As Long
            For iRow = 0 To 5
                For iCol = 0 To 5

                    'Put the row and column address in the cell.
                    saRet(iRow, iCol) = iRow.ToString() + "|" + iCol.ToString()
                Next iCol
            Next iRow

            'Set the range value to the array.
            range.Value = saRet
        End If

        'Return control of Excel to the user.
        objApp.Visible = True
        objApp.UserControl = True

        'Clean up a little.
        range = Nothing
        objSheet = Nothing
        objSheets = Nothing
        objBooks = Nothing
    End Sub

here is the sample code  here is the sample code

06-May-09 09:31 PM
Dim xlsApp As Excel.Application
Dim xlsWB As Excel.Workbook
Dim xlsSheet As Excel.Worksheet


xlsApp = New Excel.Application
xlsApp.Visible = True
xlsWB = xlsApp.Workbooks.Open(Path)
xlsSheet = xlsWB.Worksheets(1)

You can loop through xlsWB.Worksheets to access all the worksheets in the excel.

more samples refer
http://www.daniweb.com/forums/thread29055.html#
http://www.a1vbcode.com/snippet-3421.asp

easier way  easier way

06-May-09 10:16 PM
Hi

you can access excel sheet  in vb.net easily ,to this you need add a lib to your project,using Microsoft.Office.Interop.Excel;

code:

Private bodynitsApplicationClass As ApplicationClass = Nothing
Private worksheetdetail As Microsoft.Office.Interop.Excel.Worksheet = Nothing

Public Sub ProcessExcell(ByVal filename As String, ByVal sheetno As String)

If bodynitsApplicationClass Is Nothing Then
bodynitsApplicationClass = New ApplicationClass()
End If
If Not System.IO.File.Exists(filename) Then
UpdateControl("Source file does not exist inside " & filename)
Exit Sub
End If
Try
' System.Data.DataTable extracteDataTAble = GetAllDataFromExcel(filename);
Dim workbooks As Microsoft.Office.Interop.Excel.Workbook = bodynitsApplicationClass.Workbooks.Open(filename, 0, True, 5, "", "", _
False, Microsoft.Office.Interop.Excel.XlPlatform.xlWindows, vbTab, False, False, 0, _
True, 1, 0)

Dim sheets As Microsoft.Office.Interop.Excel.Sheets = workbooks.Worksheets
TGSDTSysLogger.Log("Opening excel sheet...", LogForObjects.Adidas, LogInforType.Detail)


'
get header sheet to read
worksheetdetail = DirectCast(sheets.get_Item(Integer.Parse(sheetno)), Microsoft.Office.Interop.Excel.Worksheet)
' reade very cell based on your needs


Dim RLDZ As String = DirectCast(sheet.Cells(rowindex, 22), Microsoft.Office.Interop.Excel.Range).Value2.ToString().TrimEnd()
Catch ex As Exception

Throw ex

End Try
End Sub

thank you
re  re
07-May-09 12:27 AM

u simply download the office PIA and then put two dll in bin and add refereance to yr porject

Interop.Excel.dll

Interop.Microsoft.Office.Core.dll

 

then u will be able to access workbook/worksheet in your code as follows

using Excel;

using System.Runtime.InteropServices;

 

//using ApplicationClass u can access worksheet

Excel.ApplicationClass excelApp = new Excel.ApplicationClass();

Excel.Workbook excelWorkbook = excelApp.Workbooks.Open(workbookPath, 0, false, 5, "", "", false, Excel.XlPlatform.xlWindows, "", true, false, 0, true, false, false);

Excel.Sheets excelSheets = excelWorkbook.Worksheets;

currentSheet = "sheetname";

Excel.Worksheet excelWorksheet = (Excel.Worksheet)excelSheets.get_Item(currentSheet);

//u can get cell also in code

Excel.Range destination = (Excel.Range)excelWorksheet.get_Range("A" + RowCount1.ToString(), "M"+TotalRow.ToString());

  Filip Krnjic replied to Huzefa Motiwalla
13-Jul-09 09:54 AM
Hi,

Best way to deal with Excel in VB is by using 3rd party component. It's much faster and easier way then Excel Automation. Try using GemBox http://www.gemboxsoftware.com/GBSpreadsheet.htm for working with Excel. Component is free for commercial use but with limit of 150 rows.

Here you can see a list of reason why http://www.gemboxsoftware.com/Excel-Automation.htm.

Filip
GemBox Software - http://www.gemboxsoftware.com/
Create New Account
help
Export data from a DataGridView to an Excel WorkSheet Hi guys, I use the code below to export data from a DataGridView to an Excel WorkSheet. The method works, but it is too slow. How can I improve to make it faster? Thanks in advance, Aldo. private void ExportDataToWkSht(Excel.Worksheet oSheet, DataGridView dGV) { / / Create Excel instance. / / Excel.Application oExcel = new Microsoft.Office.Interop.Excel.Application(); int colIndex = 0; foreach (DataGridViewColumn column in dGV.Columns) { if (column.Visible) { / / Export. oSheet false; / / make the unwanted columns(clickable buttons, etc.) invisible Response.Clear(); Response.ContentType = "application / ms-excel"; Response.AddHeader("Content-Disposition", "attachment;filename = BookBag.xls"); StringWriter sw = new StringWriter(); HtmlTextWriter htmlWriter = new
Open Excel File Hi All, I would like to a. open an new excel file from asp.net web application b. write few records to it c. Save the excel file with new name If this is possible please help me Thanks All You wont be able to open excel file in web application. U have to create instance of Excel Application after that u will get particular cell of excel worksheet then & then only u will be able to write in excel file. Hi, try the below one. . Microsoft.Office.Interop.Excel.Application app = new Microsoft.Office.Interop.Excel.Application(); Microsoft.Office.Interop.Excel.Workbook
How to read data from excel sheet and how to write data in to excel. I want to fill data in to text boxes from excel sheet. And I want to write results and data to excel sheet. How to write this? HI read an excel using System; using System.IO; using System.Reflection; using NUnit.Framework; using ExcelTools = Ms Office; using Excel = Microsoft.Office.Interop.Excel; namespace Tests { [TestFixture] public class ExcelSingle { [Test] public void ProcessWorkbook() { string file = @"C
into single excelsheet hello sir i try following code 3 tables are stored as diffenrent excel sheet . . i want coding for 3 tables export in single excel sheet . . inside the excel create 3 worksheets. . in the 3 worksheet stores 3 tables i try this following code da1 = new SqlCeDataAdapter("select * from purchaseOrder", con); SqlCeDataAdapter da2 = new SqlCeDataAdapter("select * from newstock", con); DataTable dt = new DataTable(); DataTable dt1 = new DataTable(); DataTable dt2 = new DataTable(); da.Fill(dt); da1.Fill(dt1); da2.Fill(dt2); Excel_FromDataTable(dt); purchaseOrderexcel
Export data in excel file using win form in visual studio 2010 I hav 1 excel file and 1 windows form in vs 2010. I have 10 fields in win form After entering details as i click on button all the details sould be saved in Excel file How to do Please reply as soon as possible. Waiting for your reply. . . Thanks xmlns = "http: / / www.w3.org / 1999 / xhtml"> < head id = "Head1" runat = "server"> < title > Export to Excel - GridView Sample < / title > < / head > < script language = "C#" runat = "server"> / / Get files from selected path private DataSource = di.GetFiles() ; gvFiles.DataBind() ; } protected void btnExportToExcel_Click( object sender, EventArgs e) { ExportToExcel() ; } / / Export to Excel from a GridView protected void ExportToExcel() { Response.Clear() ; Response.Buffer = true; Response.ContentType = "application / vnd.ms-excel" ; Response.AddHeader( "content-disposition" , "attachment;filename = MyFiles.xls" ) ; Response.Charset = "" ; this .EnableViewState = false; System.IO to export DataGrid Data to ecxel , before data you have to Include following namspaces- Microsoft.Office.Interop.Excel.Application Microsoft.Office.Interop.Excel.Worksheet Microsoft.Office.Interop.Excel.Workbook After that use this