?
Solved

Viewing an excel file

Posted on 2004-11-20
10
Medium Priority
?
301 Views
Last Modified: 2012-05-05
Hi experts.....

I am looking for an API that can open a file with certain application.
i.e. it opens test.xls with excel.exe application

Thank you

0
Comment
Question by:DarknessShadow
  • 4
  • 3
  • 2
  • +1
10 Comments
 
LVL 13

Expert Comment

by:petmagdy
ID: 12633588
something like:

        String[] runArgs = {"c:\\test\\test.xls"};
        try
        {
        Runtime.getRuntime().exec("C:\\Program Files\\Microsoft Office\\Office10\\excel.exe", runArgs);
        }
        catch(Exception ex)
        {
            ex.printStackTrace();
        }
0
 
LVL 3

Expert Comment

by:esorf
ID: 12633643
Or

 String[] runArgs = {"/C", "start", "c:\\test\\test.xls"};
and
 Runtime.getRuntime().exec("C:\\winnt\system32\cmd.exe", runArgs);

The advantage here is that you can start any document and the shell will launch the appropriate application.

Try it out from the command line with
  cmd /C start c:\test\test.xls

- Frank
0
 
LVL 13

Expert Comment

by:petmagdy
ID: 12633668
esorf,
did u tried ur solution?
I tried:

             String[] runArgs = {"/C", "start", "c:\\test\\test.xls"};
        try
        {
             Runtime.getRuntime().exec("C:\\WINDOWS\\system32\\cmd.exe", runArgs);
        }
        catch(Exception ex)
        {
            ex.printStackTrace();
        }

didn't work
0
VIDEO: THE CONCERTO CLOUD FOR HEALTHCARE

Modern healthcare requires a modern cloud. View this brief video to understand how the Concerto Cloud for Healthcare can help your organization.

 
LVL 3

Expert Comment

by:vikraman_b
ID: 12633778
Hi try this,
also have a look on this url
http://j-integra.intrinsyc.com/com/doc/java_excel/programmerguide.html

import excel.*;
import java.util.*;
 
public class JExcelGuide {
     
  public JExcelGuide(){
  }
 
  public static void main(String[] args) {
   
    try {
      JExcelGuide JExcelGuide1 = new JExcelGuide();
 
      JExcelGuide1.createWorkbook(
                                  "MyApplication",
                                  "C:\\JExB\\examples");
 
      JExcelGuide1.openWorkbook(
                                "MyApplication",
                                "C:\\JExB\\examples",
                                "saveCopyAs.xls");
    } catch(Exception e) {
      e.printStackTrace();
    } finally {
      // Release all remote objects that haven't already been garbage collected.
      com.linar.jintegra.Cleaner.releaseAll();
    }
  }
 
  /*
  * This function show how to create, save and close a new Workbook object
  * and save it.
  */
  public void createWorkbook(
                            String strNewApplicationCaption,
                            String strNewApplicationFilePath) {
    try {
      System.out.println( "createWorkbook starts." );
 
      Application _xlApp = new Application();
      System.out.println( "Application object created." );
 
      // MS Office will be invoked visually
      _xlApp.setVisible( true );
       
      // If this is set to true, MS Office requires user's interaction
      _xlApp.setDisplayAlerts( false );
       
      // operating Workbook object
      Workbooks workbooks=_xlApp.getWorkbooks();
      System.out.println( "get workbooks." );
       
      int iWorkbookCount = workbooks.getCount();
      System.out.println( "    [Workbook::Count]" + iWorkbookCount );
       
      Workbook wb1=workbooks.add( null );
      System.out.println( "add 1st workbook" );
       
      Workbook wb2=workbooks.add( new Integer(XlWBATemplate.xlWBATWorksheet) );
      System.out.println( "add 2nd workbook" );
       
      iWorkbookCount = workbooks.getCount();
      System.out.println( "    [Workbook::Count]" + iWorkbookCount );
       
      // save as default name
      wb1.save();
      System.out.println(
                        "workbook 1 saved as " +
                        wb1.getFullName());
 
      // save as default name
      wb2.save();
      System.out.println(
                        "workbook 2 saved as " +
                        wb2.getFullName());
 
      // save as custom name
      wb1.saveCopyAs(strNewApplicationFilePath + "\\saveCopyAs.xls");
      System.out.println("workbook 1 saved as " +
                        strNewApplicationFilePath +
                        "\\saveCopyAs.xls");
 
      // save as custom name using shared mode
      // You may use XlSaveAsAccessMode.xlShared.
      // To share this workbook, it must contain at
      // least one visible worksheet.
      wb1.saveAs(
                "saveAs.xls",
                null,
                null,
                null,
                null,
                null,
                XlSaveAsAccessMode.xlExclusive,
                null,
                null,
                null,
                null);
 
      System.out.println("workbook 1 saved as " +
                        strNewApplicationFilePath +
                        "saveAs.xls");
 
      // clear up Workbooks and Workbook objects
      wb1.close( new Boolean (true), null, null );
      wb2.close( new Boolean (true), null, null );
      workbooks.close();
 
      // quit application
      _xlApp.quit();
 
      System.out.println( "createWorkbook ends." );
    } catch(Exception e) {
      e.printStackTrace();
    }
  }
 
  /*
  * This function show how to open and close an existing Workbook object.
  */
  public void openWorkbook(
                          String strNewApplicationCaption,
                          String strNewApplicationFilePath,
                          String strNewWorkbookName) {
    try {
      System.out.println( "openWorkbook starts." );
 
      Application _xlApp = new Application();
      System.out.println( "Application object created." );
       
      // MS Office will be invoked visually
      _xlApp.setVisible( true );
       
      // If this is set to true, MS Office requires user's interaction
      _xlApp.setDisplayAlerts( false );
       
      // operating Workbook object
      Workbooks workbooks = _xlApp.getWorkbooks();
      System.out.println( "get workbooks." );
       
      Workbook wb = workbooks.open(
                          strNewApplicationFilePath + "\\" + strNewWorkbookName,
                          null,
                          null,
                          null,
                          null,
                          null,
                          null,
                          null,
                          null,
                          null,
                          null,
                          null,
                          null);
      System.out.println("open workbook in " + wb.getFullName());
             
      wb.activate();
      System.out.println( "Workbook is activated. " );
 
      int iWorkbookCount = workbooks.getCount();
      System.out.println( "    [Workbook::Count]" + iWorkbookCount );
 
      String strTemp = wb.getName();
      System.out.println( "    [Workbook::Name]" + strTemp );
 
      strTemp = wb.getPath();
      System.out.println( "    [Workbook::Path]" + strTemp );
 
      strTemp = wb.getAuthor();
      System.out.println( "    [Workbook::Author]" + strTemp );
 
      strTemp = wb.getSubject();
      System.out.println( "    [Workbook::Subject]" + strTemp );
 
      strTemp = wb.getTitle();
      System.out.println( "    [Workbook::Title]" + strTemp );
 
      // clear up Workbooks and Workbook objects
      wb.close( new Boolean (true), null, null );
      workbooks.close();
 
      // quit application
      _xlApp.quit();
 
      System.out.println( "openWorkbook ends." );
    } catch(Exception e) {
      e.printStackTrace();
    }
  }
}
0
 
LVL 3

Expert Comment

by:vikraman_b
ID: 12633800
all these examples belong to that url...
using Excel JAPI


import excel.*;
import java.util.*;
 
public class JExcelGuide {
     
  public JExcelGuide() {
  }
 
  public static void main(String[] args) {
         
    try {
      JExcelGuide JExcelGuide1 = new JExcelGuide();
       
      JExcelGuide1.operateRange(
                                "MyApplication",
                                "C:\\JExB\\examples",
                                "JExcelGuide.xls",
                                "JExcelGuideSheet");
    } catch(Exception e) {
      e.printStackTrace();
    } finally {
      // Release all remote objects that haven't already been garbage collected.
      com.linar.jintegra.Cleaner.releaseAll();
    }
  }
 
  /*
  * This function show how to manipulate Range object from an existing
  * Worksheet, i.e. fill out data, do calculation, invoke VBA script
  * if applicable.
  */
  public void operateRange(
                          String strNewApplicationCaption,
                          String strNewApplicationFilePath,
                          String strWorkbookName,
                          String strWorksheetName) {
    try {
      System.out.println( "operateRange starts." );
 
      Application _xlApp = new Application();
 
      // MS Office will be invoked visually
      _xlApp.setVisible( true );
       
      // If this is set to true, MS Office requires user's interaction
      _xlApp.setDisplayAlerts( false );
       
      // set caption and default path
      _xlApp.setCaption( strNewApplicationCaption );
      _xlApp.setDefaultFilePath( strNewApplicationFilePath );
       
      // operating Workbook object
      Workbooks workbooks=_xlApp.getWorkbooks();
       
      int iWorkbookCount = workbooks.getCount();
       
      Workbook wb1 = workbooks.add( null );
       
      Sheets worksheets = null;
      Worksheet ws1 = null;
       
      // get Worksheets collection
      worksheets = wb1.getWorksheets();
 
      Integer iIndex = new Integer( 1 );
      // get the 1st Worksheet(new one)
      ws1 = new Worksheet( worksheets.getItem( iIndex ) );
       
      // change the name of 1st Worksheet to "newsheet"
      ws1.setName( strWorksheetName );
       
      ws1.activate();
      System.out.println( "Activate " + strWorksheetName + " obejct." );
       
      // make Range and selected
      Range range = null;
       
      range = ws1.getRange( "B3:D6", null );
       
      range.select();
      Thread.sleep( 1000 );
       
      // set values
      Object[][] newValue = {
        { "ninja", new Boolean(false), new Double(98765.0/12345.0) },
        { "07/11/1998", new Integer(5454), new Float(22.0/7.0) },
        { new Boolean( true ), "samurai", "07/11/1999" },
        { new Integer(123), "SOAP", "Space" }
      };
      range.setValue(newValue);
      Thread.sleep( 1000 );
       
      // clear values
      range = ws1.getRange( "B3:D3", null );
       
      range.select();
      range.clearContents();
      Thread.sleep( 1000 );
       
      // set values and formula, calculate the result
      range = ws1.getRange( "A8:C8", null );
      range.select();
      int[] newValue2 = { 10, 20, 30 };
      range.setValue( newValue2 );
      Thread.sleep( 1000 );
 
      range = ws1.getRange( "D8", null );
      range.select();
      range.setValue( "=SUM(A8:C8)" );
       
      Thread.sleep( 1000 );
       
      // set range width and height
      range = ws1.getRange( "A10", null );
      range.select();
      Double dWidth = (Double)range.getColumnWidth();
      System.out.println("    [Range::DefaultColumnWidth]" + dWidth );
      double dTemp = dWidth.doubleValue();
      dTemp *= 1.5;
      dWidth = new Double(dTemp);
      range.setColumnWidth( dWidth );
 
      Double dHeight = (Double)range.getRowHeight();
      System.out.println("    [Range::DefaultRowHeight]" + dHeight );
      dTemp = dHeight.doubleValue();
      dTemp *= 1.5;
      dHeight = new Double(dTemp);
      range.setRowHeight( dHeight );
       
      Thread.sleep( 1000 );
       
      // set border weight by using Borders object
      range = ws1.getRange( "C10:D12", null );
      range.select();
       
      Borders bds = range.getBorders();
      Integer iWeight = (Integer)bds.getWeight();
      System.out.println("    [Borders::DefaultWeight]" + iWeight );
      int iTemp = iWeight.intValue();
      iTemp += 2;//maximum weight=4
      iWeight = new Integer( iTemp );
      bds.setWeight( iWeight );
       
      // set border line style by using Borders obejct
      bds.setLineStyle( new Integer( XlLineStyle.xlContinuous ) );
       
      Thread.sleep( 1000 );
 
      // set edge left border use Border object
      Integer iLineStyle=new Integer( XlLineStyle.xlDot );
       
      Border bd = bds.getItem( XlBordersIndex.xlEdgeLeft );
      bd.setLineStyle( iLineStyle );
       
      Thread.sleep( 1000 );
       
      // set Font style
      range = ws1.getRange( "B4:D5", null );
      range.select();
       
      Font ft = range.getFont();
      ft.setBold( new Boolean( true ) );
       
      ft.setItalic( new Boolean( true ) );
       
      ft.setShadow( new Boolean( true ) );
       
      ft.setUnderline( new Boolean( true ) );
       
      Thread.sleep( 1000 );
       
      // set Font color
      Double dbColor = (Double)ft.getColor();
      System.out.println("    [Font::DefaultColor]" + dbColor );
      dTemp = dbColor.doubleValue() + 32700;
      dbColor = new Double(dTemp);
      ft.setColor( dbColor );
       
      // set Font size
      Double dbSize = (Double)ft.getSize();
      System.out.println("    [Font::DefaultSize]" + dbSize );
      dTemp = dbSize.doubleValue() * 1.5;
      dbSize = new Double( dTemp );
      ft.setSize( dbSize );
       
      Thread.sleep( 1000 );
       
      // save
      wb1.setSaved( true );
      wb1.saveCopyAs( strWorkbookName );
       
      // clear up Workbooks and Workbook objects
      wb1.close( new Boolean (true), null, null );
      workbooks.close();
       
      // quit application
      _xlApp.quit();
       
      System.out.println( "operateRange ends." );
    } catch(Exception e) {
      e.printStackTrace();
    }
  }
}

0
 

Author Comment

by:DarknessShadow
ID: 12637404
Hi  petmagdy....thank you for your quick response

I tried your suggestion but it started up the Excel and closed it immediately. Therefore, I don’t know if it opened the excel file or not.

Best regards
0
 
LVL 13

Expert Comment

by:petmagdy
ID: 12637429
are u sure that the excel file u r tring to open a valid excel file?
0
 

Author Comment

by:DarknessShadow
ID: 12641428
Hi  petmagdy

the excel.exe has a problem in my PC. therfore, i tried this comand in the command prompt:

notepad d:\Java2Excel\code\test.xls

and it works fine.

However, the following java code doesn't open the file

String[] runArgs = {"D:\\Java2Excel\\code\\test.xls"};
try{Runtime.getRuntime().exec("notepad.exe", runArgs);}
catch(Exception ex)
{
            ex.printStackTrace();
}
0
 
LVL 13

Accepted Solution

by:
petmagdy earned 400 total points
ID: 12641617
>> try{Runtime.getRuntime().exec("notepad.exe", runArgs);}
to be:
try{Runtime.getRuntime().exec("c:\\FullPathTo\\notepad.exe", runArgs);}
0
 

Author Comment

by:DarknessShadow
ID: 12643026
Hi.... petmagdy.

I finally have tried the following code and it worked.
try
        {
        Runtime.getRuntime().exec("C:\\Program Files\\Microsoft Office\\OFFICE11\\Excel.EXE D:\\Java2Excel\\code\\test.xls");
}
catch(Exception ex)
        {
            ex.printStackTrace();
        }


0

Featured Post

Prep for the ITIL® Foundation Certification Exam

December’s Course of the Month is now available! Enroll to learn ITIL® Foundation best practices for delivering IT services effectively and efficiently.

Question has a verified solution.

If you are experiencing a similar issue, please ask a related question

An old method to applying the Singleton pattern in your Java code is to check if a static instance, defined in the same class that needs to be instantiated once and only once, is null and then create a new instance; otherwise, the pre-existing insta…
Java functions are among the best things for programmers to work with as Java sites can be very easy to read and prepare. Java especially simplifies many processes in the coding industry as it helps integrate many forms of technology and different d…
Viewers learn how to read error messages and identify possible mistakes that could cause hours of frustration. Coding is as much about debugging your code as it is about writing it. Define Error Message: Line Numbers: Type of Error: Break Down…
Viewers will learn about arithmetic and Boolean expressions in Java and the logical operators used to create Boolean expressions. We will cover the symbols used for arithmetic expressions and define each logical operator and how to use them in Boole…
Suggested Courses
Course of the Month17 days, 5 hours left to enroll

862 members asked questions and received personalized solutions in the past 7 days.

Join the community of 500,000 technology professionals and ask your questions.

Join & Ask a Question