Save and close excel file using C#.

I am not sure why I get the following error for the below code.  Everything seems to work otherwise.
Error found: System.Runtime.InteropServices.COMException (0x8002000B): Invalid index. (Exception from HRESULT: 0x8002000
B (DISP_E_BADINDEX))
Application _application;public void CloseFile(string filename, bool isSaveChanges)
_application.Workbooks[filename].Close(SaveChanges: isSaveChanges);

I' work with excel files with connection you can save data and  close connection Easy.
 //connection String for xls file format.
                    if (fileExtension == ".xls")
                        excelConnectionString = "Provider=Microsoft.Jet.OLEDB.4.0;Data Source=" + fileLocation + ";Extended Properties=\"Excel 8.0;HDR=Yes;IMEX=2\"";
                    //connection String for xlsx file format.
                    else if (fileExtension == ".xlsx")
                        excelConnectionString = "Provider=Microsoft.ACE.OLEDB.12.0;Data Source=" + fileLocation + ";Extended Properties=\"Excel 12.0;HDR=Yes;IMEX=2\"";
                    //Create Connection to Excel work book and add oledb namespace
                    OleDbConnection excelConnection = new OleDbConnection(excelConnectionString);
                    excelConnection.Open();
DataTable dt = new DataTable();
                    dt = excelConnection.GetOleDbSchemaTable(OleDbSchemaGuid.Tables, null);
                    if (dt == null)
                        return null;
                    String[] excelSheets = new String[dt.Rows.Count];
                    int t = 0;
                    //excel data saves in temp file here.
                    foreach (DataRow row in dt.Rows)
                        excelSheets[t] = row["TABLE_NAME"].ToString();
                        t++;
                    OleDbConnection excelConnection1 = new OleDbConnection(excelConnectionString);
                    string query = string.Format("Select * from [{0}]", excelSheets[0]);
                    using (OleDbDataAdapter dataAdapter = new OleDbDataAdapter(query, excelConnection1))
                        dataAdapter.Fill(ds);
Best Regards
Hakim.

Similar Messages

  • Save and Close excel file opened through OLE

    Hi,
    I have opened an excel file on my desktop and edited it.Now I have to save this file and close it.
    Right now , I am manually saving the file and closing it. So please give the steps to automate the process of saving and closing .
    Please find the code below for opening a file and editing.
    report zkntest2.
    INCLUDE: <line>,
             <icon>,
             <symbol>,
             ole2incl.
    DATA: g_excel_app             TYPE ole2_object,
          g_excel_workbook        TYPE ole2_object,
          g_excel_worksheet       TYPE ole2_object,
          g_excel_usedrange       TYPE ole2_object,
          g_excel_cell            TYPE ole2_object,
          g_excel_return          TYPE ole2_object.
    data :H_MAPL TYPE OLE2_OBJECT,         " list of workbooks
          H_MAP TYPE OLE2_OBJECT,          " workbook
          H_ZL TYPE OLE2_OBJECT,           " cell
          H_F TYPE OLE2_OBJECT.            " font
    CONSTANTS:c_appl(17)              TYPE c VALUE 'Excel.Application'.
    SELECTION-SCREEN BEGIN OF BLOCK blk1 with frame title text-001.
    PARAMETERS p_ofile LIKE rlgrap-filename default 'C:\layout.xls'.
    SELECTION-SCREEN END OF BLOCK blk1.
    CREATE OBJECT g_excel_app c_appl.
    CALL METHOD OF g_excel_app 'Workbooks' = g_excel_workbook.
    CALL METHOD OF g_excel_workbook 'Open'
      EXPORTING #1 = p_ofile.
    SET PROPERTY OF g_excel_app 'Visible' = 1.
    CALL METHOD OF g_excel_app 'Workbooks' = H_MAPL.
    PERFORM FILL_CELL USING  4 9 1 'Kiran'(001).
    PERFORM FILL_CELL USING  5 9 1 'Ref#'(002).
    PERFORM FILL_CELL USING  6 9 1 'Claim#'(003).
    PERFORM FILL_CELL USING  7 9 1 'Location'(004).
    FREE OBJECT g_excel_app.
    FORM FILL_CELL USING I J BOLD VAL.
      CALL METHOD OF g_excel_app 'Cells' = H_ZL EXPORTING #1 = I #2 = J.
      SET PROPERTY OF H_ZL 'Value' = VAL .
      GET PROPERTY OF H_ZL 'Font' = H_F.
      SET PROPERTY OF H_F 'Bold' = BOLD .
    ENDFORM.                    "FILL_CELL

    Try add this code below.
      CALL METHOD OF G_EXCEL_APP 'ActiveWorkbook' = G_EXCEL_WORKBOOK.
      CALL METHOD OF G_EXCEL_WORKBOOK 'SaveAs' EXPORTING #1 = '1.xls'.
      CALL METHOD OF G_EXCEL_WORKBOOK 'Close'.
      CALL METHOD OF G_EXCEL_APP 'Quit'.
      FREE G_EXCEL_APP.

  • Automatically open, save and close excel?

    I need import data from Excel to SQL.
    Now, I use tSQL to directly read the excel files and transform to the SQL table.
    As the user Excel is not a good format for SQL to read, I need use formula to transform the excel to be a SQL readable format.
    Now, I add a sheet to copy the data from the sheet which user input the data and then ask the user to copy the excel to a specific location for import.
    However, this will make the data in the excel double and result a large excel file.
    I am thinking if it is possible to create a excel to use formula to copy the data from another excel.
    Then, I need find some method to open that excel, let the content refresh from the source excel, save and close it.
    Then I can directly use this excel for data import.
    Is there any simple way to do so? I don't know marco much...
    Ivan

    No formula could do this (Automatically open, save and close excel).
    You need to recode a marco or write a macro. Why donot you ask in msdn?
    http://social.msdn.microsoft.com/Forums/en-US/home?forum=exceldev&filter=alltypes&sort=lastpostdesc
    example:
    Sub auto_open()
    Application.OnTime Now + TimeValue("00:01:00"), "wswx"
    End Sub
    Sub
    wswx() If Not ThisWorkbook.Saved
    Then ThisWorkbook.Save
    ThisWorkbook.Close
    End Sub
    KR

  • Save and close InDesign file CS4 JS

    Hi, I need to save and close InDesign file after export pdf was done. Once export is complete the script opens the pdf file and the script gets interrupted. Here what I was trying and I am not sure if it even in the right direction:
    #targetengine "session"
    main();
    function main(){
        var myApplicationEventListener = app.eventListeners.add("afterExport",
        mySaveInDesign, false);
        var myDocumentEventListener = app.documents.item(0).eventListeners.add
        ("afterExport", mySaveInDesign, false);
        app.scriptPreferences.version = 6.0;
    var myEventNames = ["afterExport"] ;
    function mySaveInDesign(myEvent){
        var myDocument = myEvent.parent;
        saveInDesign ();
    function saveInDesign (){
        //myDocument.save(myDocument);
        app.activeDocument.save(myDocument);
        app.activeDocument.close(myDocument);
    Your help is highly appreciated.
    Yulia

    Save either takes no argument (equivalent to the File/Save menu option) or a file path, equivalent to File/Save As.
    So, your save commands aren't going to work as written. You either need just save(); or save(myDocument.fullName);
    Dave

  • Welcome window problem.  appears every time i save and close a file of photoshop

    How to fix a bug regarding welcome window. this window appears every time i save and close a file of photoshop, its started after the last update 2014.2.0

    See this document: Troubleshoot Welcome Screen in Photoshop
    Scroll all the way down to the bottom. There's a check box "Don't Show Welcome Screen Again"
    You can relaunch the screen at a later date by selecting Help>Welcome Screen...
    ~ Arpit

  • Hello, Indesign 6 will not allow me to save and close my file

    Hello, Indesign 6 will not allow me to save and close my file

    Try exporting to .idml. If that works, openthe .idml and save as a new .indd.
    If it doesn't work, force quit ID and then restart. Auto-recovery should kick in and reopen the file at about the last state, then try again.

  • Open, Write and Close the file using Powershell

    Hi All,
    I need to create/open a file and write some data into it and close that file.
    Could anyone please help me with this.
    Thanks.

    You don't need to explicitly create, open, or close a file in Powershell.  Here are some ways to write to a file, in addition to New-Item:
    $text = 'Hello World'
    # Create file:
    $text | Set-Content 'file.txt'
    #or
    $text | Out-File 'file.txt'
    #or
    $text > 'file.txt'
    # Append to file:
    $text | Add-Content 'file.txt'
    #or
    $text | Out-File 'file.txt' -Append
    #or
    $text >> 'file.txt'
    Grant Ward, a.k.a. Bigteddy
    The problem with Out-File is that it works like the console. When text is output, it will be truncated if it is wider than the default. So if you are looking for something where you need to store lots of long strings, then you may want to choose a different
    route, or ensure than you specify a width for your output.
    http://technet.microsoft.com/en-us/library/ee176924.aspx
    For example to get 200 characters of width:
    $text | Out-File
    'myfile.txt' -width 200
    I do not know for certain if there is a limit to how wide it can be. I also assume the default is the standard console width (80 characters I believe.)

  • How to continuous data acquisition and save to an excel file using vc++

    Hi,
    I’m trying to build an MFC application with MSVC++6, where I would continuously acquire
    samples from 2 channels of a USB-6289. I’m using the DAQmx C functions.  I use the following codes to continuously get data:
    DAQmxErrChk(DAQmxCreateAIVoltageChan(taskHandle,"Dev1/ai0,Dev1/ai1","",DAQmx_Val_Cfg_Default,-10.0,10.0,DAQmx_Val_Volts,NULL));
    DAQmxErrChk(DAQmxReadAnalogF64(taskHandle,1000,-1,DAQmx_Val_GroupByChannel,data,2000,&read,NULL));
            DAQmxErrChk
    (DAQmxRegisterEveryNSamplesEvent(taskHandle,DAQmx_Val_Acquired_Into_Buffer,1000,0,EveryNCallback,NULL));
            DAQmxErrChk (DAQmxRegisterDoneEvent(taskHandle,0,DoneCallback,NULL));
     static int32 EveryNCallback(TaskHandle taskHandle, int32 everyNsamplesEventType, uInt32 nSamples, void *callbackData)
        int32       error=0;
        char    errBuff[2048]={'\0'};
        static int  totalRead=0;
        int32       read=0;
        float64     data[1000];
        // DAQmx Read Code
        DAQmxErrChk(DAQmxReadAnalogF64(taskHandle,1000,-1,DAQmx_Val_GroupByChannel,data,2000,&read,NULL));
       if( read>0 ) {
        fflush(stdout);
            Error:
        if( DAQmxFailed(error) ) {
            DAQmxGetExtendedErrorInfo(errBuff,2048);
            DAQmxStopTask(taskHandle);
            DAQmxClearTask(taskHandle);
                return 0;
    static int32 CVICALLBACK DoneCallback(TaskHandle taskHandle, int32 status, void *callbackData)
        int32   error=0;
        char    errBuff[2048]={'\0'};
        // Check to see if an error stopped the task.
        DAQmxErrChk (status);
    Error:
        if( DAQmxFailed(error) ) {
            DAQmxGetExtendedErrorInfo(errBuff,2048);
                //MessageBox("errors in DoneCallBack");
            DAQmxClearTask(taskHandle);
            //MessageBox(errBuff);
        return 0;
    I have two questions:
    1. how to save the data into an excel file? Can anyone show me some sample codes please?
    2.Are
    the data acquired from the two channels simultaneously? If I set the
    starting time at 0, sample frequency 1khz, can I directly multiply the
    sample number by 0.001 to calculate time (as shown below)?
    Time    channel1  channel2
    0.001    d11           d21
    0.002    d12           d22
    Thank you! 

    You aren't going to get much help with Visual C++ programing when asking questions in the LabVIEW forum. 
    Try the Measurement Studio for Visual C++ forum.
    Message Edited by Ravens Fan on 12-05-2008 04:24 PM

  • How do I read a range of data from an open and "live" Excel file using LV7.0 Express

    I need to interface with software which continuously (once per second) writes a new array to a fixed location in an open Excel file. I would like to read this data into Labview from where I can do what I like with it. I am relatively new to LabView and have tried all "Read Data" examples that come with the product, Active examples seem very unclear. Anyone got any samples/suggestions to get me started?
    Attachments:
    Changing_Excel_file.xls ‏17 KB

    It is possible but might be a little bit complicated. Does your application opens the Excel file or Excel file was opened through Excel or another application already?
    In the first senario, once the excel is opened, start reading the data, do not close the report file (dispose the report) or close the excel file
    In the second senario, it is a little bit more complicated. You need to use low level Excel ActiveX functions. The procedure is:
    1. Open reference to Excel
    2. Activate the desired workbook if it is already opened
    or open a new file
    3. Activate the sheet containing the data
    4. Read the data
    5. Loop if necessary (step 2 if diff wb, step 3 if diff sht, 4 if same sheet)
    6. Close Excel reference (Very important, close the
    ref only, do not use Application.Exit to exit Excel).
    Hope this helps,
    -Joe

  • XML to Excel file using dom4j

    hi!
    i'm new with dom4j and i don't have any idea on how to do the following task:
    i have an xml document which i have to save as an excel file using dom4j. my problem is i also have to insert records in the middle of the file. is it possible?
    sample layout:
    Worksheet Header (also have to plot a value)
    Column Header (also have to plot a value)
    -- need to insert records here --
    Sub-total row
    Total row
    i would appreciate any help from you guys...
    thanks in advance...

    Hi there!
    First I haven't seen any application that uses dom4j to write excel's file, but I can recommend you to use Apache's POI to write and read from any excel's file, actually I'm working rigth now with it, and works fine with Office 2003.
    http://jakarta.apache.org/poi/hssf/
    For the XML you can use what ever you feel confortable with, dom4j, jdom, etc. I really like jdom thougth

  • How to read the excel file using webdynpro abap?

    Hi,
    how to read and modify excel file using webdynpro abap?
    Regards,
    Pavani

    For reading excel file follow the steps :
    1. Use a File upload UI element and bind it with xstring.
    2. Now your excel will be uploaded and stored in Xstring.
    3. Convert Xstring to String data using FM 'HR_KR_XSTRING_TO_STRING'.
    4. Now split the string at new line so as to make an internal table .
      Ex . SPLIT l_string  AT cl_abap_char_utilities=>newline INTO TABLE it_table.
      here it_table is type table of string.
    5.now loop at the internal table and separate the content of this table separated by tab.
      Ex. SPLIT wa_table AT cl_abap_char_utilities=>horizontal_tab INTO TABLE it_new.
    it_new type string_table.
    6. For more info , refer this thread :
    Re: How to upload excel file in Webdynpro application using ABAP

  • Use VBA and Excel to open Dreamweaver HTML (CS5), find and replace text, save and close

    I wish to use VBA and Excel to programmatically open numbered Dreamweaver HTML (CS5) and find and replace text in the code view of these files, save and close them.
    I have  5000 associations between Find: x0001 and Replace: y0001 in an Excel sheet.
    I have the VBA written but do not know how to open, close and save the code view of the ####.html files. Please ... and thank you...
    [email protected]

    This is actually the code view of file ####.html that I wish to find and replace programmatically where #### is a four digit number cataloguing each painting.... In 1995 I thought this was clever... maybe not so clever now :>)) Thank you for whatever you can do Rob!
    !####.jpg!
    h2. "Name####"
    Oils on acrylic foundation commercial canvas - . xx X xx (inches) Started
    Back of the Painting In Progress </p> </body> </html>
    Warmest regards,
    Phil the Forecaster, http://philtheforecaster.blogspot.ca/ and http://phils-market.blogspot.ca/

  • Keep getting corrupted temp save file when I save and close.

    When I save and close a numbers spreadsheet, about 20% of the time I will be left with the normal file and a weird temporary file with a "~" on the end of the file name.  I can't delete the file or do anything with it.  It will let me open it, but even when I save it still says I cant delete because the file is in use.
    Example-
    Work on spreadsheet1.  Hit save and then close.
    In finder I am left with-
    spreadsheet1
    spreadsheet1~
    "spreadsheet1" is the correct file and it works and functions normally, but "spreadsheet1~" is corrupt and I cant seem to delete it.  I always get "The operation can’t be completed because the item “spreadsheet1~” is in use.
    What is causing this and how can I get rid of those files?

    I think I would ignore the files and not worry about them.  Are you experiencing any undesirable effects of these files-- aside from seeing them there?

  • How can I create an csv/excel file using pl/sql and then sending that file

    How can I create an csv/excel file using pl/sql and then sending that file to a clients site using pl/sql?
    I know how to create the csv/excel file but I can't figure out how I would get it to the clients site.

    968776 wrote:
    How can I create an csv/excel file using pl/sql and then sending that file to a clients site using pl/sql?
    I know how to create the csv/excel file but I can't figure out how I would get it to the clients site.You are trying to do it at a wrong place..
    Whay do you want database (pl/sql) code to do these things?
    Anyhow, you may be interested in :
    {message:id=9360007}
    {message:id=9984244}

  • Writing into Excel file using PL/SQL and formatting the excel file

    Hi,
    I am writing into a excel file using PL/SQL and I want to make the first line bold on the excel. Also let me know if there are any other formatting options when writing into excel.
    Regards,
    -Anand

    I am writing into a excel file using PL/SQL
    Re: CSV into Oracle and Oracle into CSV
    check that thread or search in this forum...

Maybe you are looking for