Store data in mysql after reading from excel files

i am trying to make o program where i will read the data from excel files and i will store them in a database. I am using eclipse as editor and mySQL. I am using APACHE POI to read the excel files and JDBC for the connection. The excel files have the structure as shown below:
ID NAME SALARY STREET
321 TIM 1254 14 avenue
121 PAUL 1265 28h oktovriou
432 NICK 4521 papaflessa
I have of course plenty of such files which contains many more rows and columns. The purpose of my program is to read the data, create table named as the name of the excel file and the fields of each table to be the first rows of the excel file. Afterwards the values will be the rest data of the excel file. In the code below i have managed to read them, show the data in the console. Afterwrds i am trying to call a database with JDBC but there i have problem when i create the table.
try
String[] allFields;
String createTableStr = "CREATE TABLE" + createTableStr
+ "(" + org.apache.commons.lang3.StringUtils.join(allFields,
",") + ")";
Could anyone help me?
Thank you in advance!:)
import java.io.FileInputStream;
import java.io.IOException;
import java.util.ArrayList;
import java.util.HashMap;
import java.util.Iterator;
import java.util.List;
import org.apache.poi.hssf.usermodel.HSSFCell;
import org.apache.poi.hssf.usermodel.HSSFRow;
import org.apache.poi.hssf.usermodel.HSSFSheet;
import org.apache.poi.hssf.usermodel.HSSFWorkbook;
import org.apache.commons.lang3.StringUtils;
import org.apache.poi.ss.usermodel.Cell;
import java.sql.Connection;
import java.sql.DriverManager;
import java.sql.SQLException;
import java.sql.Statement;
public class exam1 {
@SuppressWarnings({ "unchecked", "unchecked" })
static void main (String[] args) throws Exception {
String filename = "C:\\Users\\Efi\\Documents\\test5.xls";
List sheetData = new ArrayList();
FileInputStream fis = null;
try {
fis = new FileInputStream(filename);
HSSFWorkbook workbook = new HSSFWorkbook(fis);
HSSFSheet sheet = workbook.getSheetAt(0);
Iterator rows = sheet.rowIterator();
while (rows.hasNext()) {
HSSFRow row = (HSSFRow) rows.next();
Iterator cells = row.cellIterator();
List data = new ArrayList();
while (cells.hasNext()) {
HSSFCell cell = (HSSFCell) cells.next();
data.add(cell);
sheetData.add(data);
} catch (IOException e) {
e.printStackTrace();
} finally {
if (fis != null) {
fis.close();
showExcelData(sheetData);
@SuppressWarnings("unused")
HashMap<String, String> tableFields = new HashMap();
for (int i=0; i<sheetData.size();i++){
List list = (List) sheetData.get(i);
for (int j=0; j<list.size(); j++){
Cell cell = (Cell) list.get(j);
if (cell.getCellType() == Cell.CELL_TYPE_NUMERIC) {
System.out.print(cell.getNumericCellValue());
}else if(cell.getCellType()==Cell.CELL_TYPE_STRING) {
System.out.print(cell.getRichStringCellValue());
} else if(cell.getCellType()==Cell.CELL_TYPE_BOOLEAN) {
System.out.print(cell.getBooleanCellValue());
if (j < list.size() - 1) {
System.out.print(", ");
private static void showExcelData(List sheetData) {
@SuppressWarnings("unchecked")
private HashMap parseExcelData (List sheetData){
HashMap<String,Integer> tableFields = new HashMap();
List list = (List) sheetData.get(0);
for (int j=0; j<list.size(); j++){
Cell cell=(Cell) list.get(j);
tableFields.put(cell.getStringCellValue(),cell.getCellType());
return tableFields;
@SuppressWarnings({ "unchecked", "unchecked", "unchecked", "unchecked", "unused" })
private String getCreateTable(String tablename, HashMap<String, Integer> tableFields){
Iterator iter = tableFields.keySet().iterator();
String str="";
String[] allFields = new String[tableFields.size()];
int i = 0;
while (iter.hasNext()){
String fieldName = (String) iter.next();
Integer fieldType=(Integer)tableFields.get(fieldName);
switch (fieldType){
case Cell.CELL_TYPE_NUMERIC:
str=fieldName + "INTEGER";
break;
case Cell.CELL_TYPE_STRING:
str= fieldName + "VARCHAR(255)";
break;
case Cell.CELL_TYPE_BOOLEAN:
str=fieldName + "INTEGER";
break;
allFields[i++]= str;
return str;
public Connection getConnection() throws SQLException {
try {
Class.forName("com.mysql.jdbc.Driver");
Connection con = (Connection) DriverManager.getConnection("jdbc:mysql://localhost:3306/kainourgia","root", "root");
Statement stmt = con.createStatement();
try
System.out.println( "Use the database..." );
stmt.executeUpdate( "USE kainourgia;" );
catch( SQLException e )
System.out.println( "SQLException: " + e.getMessage() );
System.out.println( "SQLState: " + e.getSQLState() );
System.out.println( "VendorError: " + e.getErrorCode() );
try
String[] allFields;
String createTableStr = "CREATE TABLE" + createTableStr
+ "(" + org.apache.commons.lang3.StringUtils.join(allFields,
*",") + ")";*
System.out.println( "Create a new table in the database" );
stmt.executeUpdate( createTableStr );
catch( SQLException e )
System.out.println( "SQLException: " + e.getMessage() );
System.out.println( "SQLState: " + e.getSQLState() );
System.out.println( "VendorError: " + e.getErrorCode() );
catch( Exception e )
System.out.println( ((SQLException) e).getSQLState() );
System.out.println( e.getMessage() );
e.printStackTrace();
return null;
}

Please don't multipost! Also crossposted: http://www.java-forums.org/jdbc/71612-store-data-mysql-after-reading-excel-files.html
Mod: I'm locking this thread.

Similar Messages

  • .exe reading from Excel files

    Hi everybody,
    I know similar questions have been asked lots of times but while searching the forum didn't find an anwer to my problem.
    I created an exe file (using exe4j) of a java application which reads form Excel files. Although it works when I run it from my editor, when running the exe file it cant find the Excel file. More specifically I have this error:
    "java.sql.SQLException: [Microsoft][ODBC Driver Manager] Data source name not found and no default driver specified"
    In order to read from excel files I use POI. I used it so as not to use ODBC driver and make it possible to run in every computer. When adding the driver, the exe works.Do you know a way to make it work without having to install the Driver?
    Thanks in Advance

    You need database drivers to read excel spread sheets?
    Also, why did you make it an exe? just jar it and be done with it.

  • Error in reading from excel file

    hi,
    I have written a program which reads from excel file
    and based on the value of the column i have to do something.
    Everything is fine but when i run it, it produces an error message
    Exception: For input string: "851.0"
    the value 851.0 is acually the value of the first column.
    Here is the code and i hope someone can help me to find the solution
    try{
                               Class.forName("sun.jdbc.odbc.JdbcOdbcDriver");
                               Connection con = DriverManager.getConnection( "jdbc:odbc:exceltest" );
                               Statement st = con.createStatement();
                               ResultSet rs = st.executeQuery( "Select * from [Sheet1$] " );
                               ResultSetMetaData rsmd = rs.getMetaData();
                               int numberOfColumns = rsmd.getColumnCount();
                               while (rs.next()) {
                                            for (int i = 1; i <= numberOfColumns; i++) {
                                                 if(i==1){
                                                            String columnValue1 = rs.getString(i);
                                                            custNo =Integer.parseInt(columnValue1);
                                                           // System.out.println(columnValue1);     
                                                            found=search(custNo);
                                                            if (found==false)
                                                                 insert(custNo);
                                                            System.out.println(columnValue1);     
                                                 else if (i == numberOfColumns && found==false)
                                                           String columnValue = rs.getString(i);
                                                           if(columnValue=="a")
                                                                incrementCusta();
                                                           else if (columnValue=="b")
                                                                incrementCustB();
                                                           else if(columnValue=="c")
                                                                incrementCustc();
                                                           else if(columnValue=="d")
                                                                incrementCustId();
                                            System.out.println("");     
                                       st.close();
                                       con.close();
                                      } catch(Exception ex) {
                                           System.err.print("Exception: ");
                                           System.err.println(ex.getMessage());
                                 }

    Maybe 851.0 is float value, not string.
    Try Object columnValue1 =
    rs.getObject(i); instead of String
    columnValue1 = rs.getString(i);
    You are absolutely right i actually change the line
    custNo =Integer.parseInt(columnValue1);
    into
    custNo =Double.parseDouble(columnValue1);
    Thanks alot :)

  • How to  read from excel file and write it using implicit jsp out object

    our code is as below:Please give us proper solution.
    we are reading from Excel file and writing in dynamicaly generated Excel file.it is writing but not as original excel sheet.we are using response.setContentType and response.setHeader for generating pop up for saveing the original file in to dynamically generated Excel file.
    <%@ page contentType="application/vnd.ms-excel" %>
    <%     
         //String dLoadFile = (String)request.getParameter("jspname1");
         String dLoadFile = "c:/purge_trns_nav.xls" ;
         File f = new File(dLoadFile);
         //set the content type(can be excel/word/powerpoint etc..)
         response.setContentType ("application/msexcel");
         //get the file name
         String name = f.getName().substring(f.getName().lastIndexOf("/") + 1,f.getName().length());
         //set the header and also the Name by which user will be prompted to save
         response.setHeader ("Content-Disposition", "attachment;     filename="+name);
         //OPen an input stream to the file and post the file contents thru the
         //servlet output stream to the client m/c
              FileInputStream in = new FileInputStream(f);
              //ServletOutputStream outs = response.getOutputStream();
              int bit = 10;
              int i = 0;
              try {
                        while (bit >= 0) {
                        bit = in.read();
                        out.write(bit) ;
    } catch (IOException ioe) { ioe.printStackTrace(System.out); }
              out.flush();
    out.close();
    in.close();     
    %>

    If you want to copy files as fast as possible, without processing them (as the DOS "copy" or the Unix "cp" command), you can try the java.nio.channels package.
    import java.nio.*;
    import java.nio.channels.*;
    import java.io.*;
    import java.util.*;
    import java.text.*;
    class Kopy {
         * @param args [0] = source filename
         *        args [1] = destination filename
        public static void main(String[] args) throws Exception {
            if (args.length != 2) {
                System.err.println ("Syntax: java -cp . Kopy source destination");
                System.exit(1);
            File in = new File(args[0]);
            long fileLength = in.length();
            long t = System.currentTimeMillis();
            FileInputStream fis = new FileInputStream (in);
            FileOutputStream fos = new FileOutputStream (args[1]);
            FileChannel fci = fis.getChannel();
            FileChannel fco = fos.getChannel();
            fco.transferFrom(fci, 0, fileLength);
            fis.close();
            fos.close();
            t = System.currentTimeMillis() - t;
            NumberFormat nf = new DecimalFormat("#,##0.00");
            System.out.print (nf.format(fileLength/1024.0) + "kB copied");
            if (t > 0) {
                System.out.println (" in " + t + "ms: " + nf.format(fileLength / 1.024 / t) + " kB/s");
    }

  • Read from excel file stops at column 5(E) returns error at data variant function

    hi,
    i am read an excel file approx 15 rows by 16 rows.
    The vi works fine upto 5 rows and 5 columns and prints data on front panel after using data variant.
    The Cell range are also seems to be correct for higher rows/columns but then the errors occurs at data variant to 2d dbl stage.
    Any idea what might be wrong in the vi
    Thanks
    chintan

    Thanks for the reply.
    I found out what was wrong the data types should be the string type and i was using DBL.

  • CLIENT_OLE2 date formatting problem while reading from Excel

    I have installed webutil package and tested that everything works by running webutil_demo as well as WU_TEST_106 form. Then I had implemented reading from Excel sp. sheet using Oracle note 813535.1 (This note has OLE2 code sample on how to read an Excel file). Everything fine till now. The problem started when I have a date fiield to read from Excel. The field where the value is going to has format mask of 'DD-MM-RRRR'. When the date is displayed in the form, it shows '01-AUG-0009' instead of '01-AUG-2009'. I tried changing the date format to different formats in Excel but no go. I found one blog which stated that treat the date as number and use e.g. "cell_date_value:=to_date('01/01/1900','DD/MM/YYYY')+client_OLE2.get_num_property(cel,,'Value')+2" but it too did not change the display. Then I tried debugging and stepping through the code..the only thing I noticed that OLE2 function displayed the date with 2 digit year as 09 and when the code completed execution, the date went back to '01-AUG-0009'. Casting with 4 digit year at every step in the code is not helping to change final date display correctly. Any idea?!!!

    Hi,
    While reading the date column from excel, try using
         m_col_val := OLE2.get_char_property(Workcell,'Text');
    Instead of
         m_col_val := OLE2.get_char_property(Workcell,'Value');
    I think you problem will be solved...
    hello...i meant client_OLE2
    Regards
    Dora
    Edited by: Dora on Sep 16, 2009 11:05 AM

  • Getting an Error after reading a excel file

    hi
    I am reading a excel file using POI
    my code is
    package businessLogic;
    import java.io.FileInputStream;
    import java.io.IOException;
    import java.io.InputStream;
    import org.apache.poi.hssf.eventusermodel.HSSFEventFactory;
    import org.apache.poi.hssf.eventusermodel.HSSFListener;
    import org.apache.poi.hssf.eventusermodel.HSSFRequest;
    import org.apache.poi.hssf.record.BOFRecord;
    import org.apache.poi.hssf.record.BoundSheetRecord;
    import org.apache.poi.hssf.record.LabelSSTRecord;
    import org.apache.poi.hssf.record.NumberRecord;
    import org.apache.poi.hssf.record.Record;
    import org.apache.poi.hssf.record.RowRecord;
    import org.apache.poi.hssf.record.SSTRecord;
    import org.apache.poi.poifs.filesystem.POIFSFileSystem;
    * This example shows how to use the event API for reading a file.
    public class EventExample implements HSSFListener
    private SSTRecord sstrec;
    * This method listens for incoming records and handles them as required.
    * @param record The record that was found while reading.
    public void processRecord(Record record)
         try
    switch (record.getSid())
    // the BOFRecord can represent either the beginning of a sheet or the workbook
    case BOFRecord.sid:
    BOFRecord bof = (BOFRecord) record;
    if (bof.getType() == bof.TYPE_WORKBOOK)
    System.out.println("Encountered workbook");
    // assigned to the class level member
    } else if (bof.getType() == bof.TYPE_WORKSHEET)
    System.out.println("Encountered sheet reference");
    break;
    case BoundSheetRecord.sid:
    BoundSheetRecord bsr = (BoundSheetRecord) record;
    System.out.println("New sheet named: " + bsr.getSheetname());
    break;
    case RowRecord.sid:
    RowRecord rowrec = (RowRecord) record;
    System.out.println("Row found, first column at " + rowrec.getFirstCol() + " last column at " + rowrec.getLastCol());
    break;
    case NumberRecord.sid:
    NumberRecord numrec = (NumberRecord) record;
    System.out.println("Cell found with value " + numrec.getValue()+ " at row " + numrec.getRow() + " and column " + numrec.getColumn());
    break;
    // SSTRecords store a array of unique strings used in Excel.
    case SSTRecord.sid:
    sstrec = (SSTRecord) record;
    for (int k = 0; k < sstrec.getNumUniqueStrings(); k++)
    System.out.println("String table value " + k + " = " + sstrec.getString(k));
    break;
    case LabelSSTRecord.sid:
    LabelSSTRecord lrec = (LabelSSTRecord) record;
    System.out.println("String cell found with value " + sstrec.getString(lrec.getSSTIndex()));
    break;
         catch(Exception ex)
    * Read an excel file and spit out what we find.
    * @param args Expect one argument that is the file to read.
    * @throws IOException When there is an error processing the file.
    public static void main(String[] args) throws IOException
    // create a new file input stream with the input file specified
    // at the command line
         try
              FileInputStream fin = new FileInputStream("C:/FTERPending/FTER format.xls");
              // create a new org.apache.poi.poifs.filesystem.Filesystem
              POIFSFileSystem poifs = new POIFSFileSystem(fin);
              //      get the Workbook (excel part) stream in a InputStream
              InputStream din = poifs.createDocumentInputStream("Workbook");
              // construct out HSSFRequest object
              HSSFRequest req = new HSSFRequest();
              // lazy listen for ALL records with the listener shown above
              req.addListenerForAllRecords(new EventExample());
              // create our event factory
              HSSFEventFactory factory = new HSSFEventFactory();
              //      process our events based on the document input stream
              factory.processEvents(req, din);
              // once all the events are processed close our file input stream
              fin.close();
              // and our document input stream (don't want to leak these!)
              din.close();
              System.out.println("done.");
         catch(Exception ex)
    It prints correctly the output at the console and after that it throws an exception as
    java.lang.reflect.InvocationTargetException
         at sun.reflect.NativeConstructorAccessorImpl.newInstance0(Native Method)
         at sun.reflect.NativeConstructorAccessorImpl.newInstance(Unknown Source)
         at sun.reflect.DelegatingConstructorAccessorImpl.newInstance(Unknown Source)
         at java.lang.reflect.Constructor.newInstance(Unknown Source)
         at org.apache.poi.hssf.record.RecordFactory.createRecord(RecordFactory.java:224)
         at org.apache.poi.hssf.eventusermodel.HSSFEventFactory.genericProcessEvents(HSSFEventFactory.java:183)
         at org.apache.poi.hssf.eventusermodel.HSSFEventFactory.processEvents(HSSFEventFactory.java:101)
         at businessLogic.EventExample.main(EventExample.java:103)
    Caused by: java.lang.ArrayIndexOutOfBoundsException
         at java.lang.System.arraycopy(Native Method)
         at org.apache.poi.hssf.record.UnknownRecord.<init>(UnknownRecord.java:62)
         at org.apache.poi.hssf.record.SubRecord.createSubRecord(SubRecord.java:57)
         at org.apache.poi.hssf.record.ObjRecord.fillFields(ObjRecord.java:99)
         at org.apache.poi.hssf.record.Record.fillFields(Record.java:90)
         at org.apache.poi.hssf.record.Record.<init>(Record.java:55)
         at org.apache.poi.hssf.record.ObjRecord.<init>(ObjRecord.java:61)
         ... 8 more
    I am not getting why this exception is cming
    can anyone help me pls reply

    Does your Excel file has the "AutoFilter" activated?
    If that is the problem, you have here a solution for reading a file with AutoFilter : http://article.gmane.org/gmane.comp.jakarta.poi.user/4690

  • How to import data into a Z table from excel file?

    hi,
    i have a custom created Z table into which i want to import some data from an excel file. which function can i use to do so because SE16 allows me to insert data only one by one via a data entry screen. this is time consuming. i want to import data from excel file so that its faster.

    HI,
    this program uploads data from excel and modifies ztable,(inserts records into ztable), check this and modify according to ur requirement)
    This program uploads material number from excel sheet and does
    ******modifications to material number if required by the user
    ******and updates the table zmatnr with new material against the old material number
    REPORT  zmat_no message-id zebg.
    TYPE-POOLS  truxs.
    TABLES:zmatnr.
    DATA : itab LIKE alsmex_tabline OCCURS 0 WITH HEADER LINE.
    DATA row LIKE alsmex_tabline-row.
    data : g_matnr like mara-matnr.
    data : count type i.
    data : itab_count type i.
    data : gi_final like zmatnr occurs 0 with header line.
    *data : begin of gi_final occurs 0,
          mat_old like mara-matnr,
          mat_new like mara-matnr,
          end of gi_final.
    ***********************Selection Screen*************************
    SELECTION-SCREEN BEGIN OF BLOCK b1 WITH FRAME TITLE text-001.
    PARAMETER : pfname LIKE rlgrap-filename OBLIGATORY.
    select-options : records for count.
    SELECTION-SCREEN END OF BLOCK b1.
    *********************At Selection Screen*************************
    AT SELECTION-SCREEN ON VALUE-REQUEST FOR pfname.
      PERFORM search.
    START-OF-SELECTION.
    perform process.
    form process.
      CALL FUNCTION 'ALSM_EXCEL_TO_INTERNAL_TABLE'
        EXPORTING
          filename                = pfname
          i_begin_col             = 1
          i_begin_row             = 2
          i_end_col               = 12
          i_end_row               = 65000
        TABLES
          intern                  = itab
        EXCEPTIONS
          inconsistent_parameters = 1
          upload_ole              = 2
          OTHERS                  = 3.
      IF sy-subrc <> 0.
    MESSAGE ID SY-MSGID TYPE SY-MSGTY NUMBER SY-MSGNO
            WITH SY-MSGV1 SY-MSGV2 SY-MSGV3 SY-MSGV4.
      ENDIF.
      describe table itab lines itab_count.
       row = 1.
      loop at itab.
        if itab-row <> row.
          append gi_final.
          clear gi_final.
        endif.
        case itab-col.
          when '1'.
          CLEAR G_MATNR.
          gi_final-OLD_MATNR = itab-value.
          CONCATENATE 'NEW' gi_final-old_matnr INTO itab-value.
            gi_final-new_MATNR = itab-value.
          endcase.
        row = itab-row.
      append gi_final.
      clear gi_final.
      endloop.
      CALL FUNCTION 'PROGRESS_INDICATOR'
      EXPORTING
        I_TEXT  = 'File Has Been Successfully Uploaded from Workstation ' .
      if not gi_final[] is initial.
        if not records-low is initial .
          if not records-high is initial.
            records-high = records-high + 1.
            DESCRIBE TABLE gi_final LINES count.
            IF records-high < count.
              DELETE gi_final FROM records-high TO count.
            ENDIF.
            IF records-low <> 1.
              IF records-low <> 0.
                DELETE gi_final FROM 1 TO records-low.
              ENDIF.
            ENDIF.
          endif.
        endif.
      endif.
      IF NOT GI_FINAL[] IS INITIAL.
        CALL FUNCTION 'PROGRESS_INDICATOR'
         EXPORTING
           I_TEXT  = 'Processing zmatnr table'
           I_OUTPUT_IMMEDIATELY = 'X'.
          if itab_count <> count.
             message i000 with 'records are not matching'.
             exit.
          else.
             modify zmatnr from table gi_final.
             message i000 with 'data base table modified successfully'.
          endif.
      endif.
    endform.
    *&      Form  search
          text
    -->  p1        text
    <--  p2        text
    FORM search .
      CALL FUNCTION 'KD_GET_FILENAME_ON_F4'
        EXPORTING
          static    = 'X'
        CHANGING
          file_name = pfname.
    ENDFORM.                    " search
    regards
    siva

  • BO Data Services - Reading from excel file and writing to SQL Server Table

    Hi,
    I would like to read data from an excel file and write it to a SQL Server Data base table without making any transformations using Data Services. I have created an excel file format as source and created target table in SQL Server. The data flow will just have source and target. I am not sure how to map the columns between source and target. Appreciate your quick help in providing a detailed steps of mapping.
    Regards,
    Ramesh

    Ramesh,
    were you able to get this to work? if not, let me know and I can help you out with it.
    Lynne

  • Read from Excel file in SP2013

    Hi,
    I have a requirement to read data from a formatted Excel file which is located in a document library, and put the contents in a List via code. This functionality should check - if he record exists  update the list item, if not create a new list
    item.
    I have installed the PIA assemblies and have referenced the excel iterop services dll from
    C:\Program Files (x86)\Microsoft Visual Studio 11.0\Visual Studio Tools for Office\PIA\Office15\Microsoft.Office.Interop.Excel.dll
    I am trying to use the excel interop services but getting the below error :
    public void readexcelfromExcelOp()
    using (ClientContext clientContext = new ClientContext("http://development002/"))
    List docList = clientContext.Web.Lists.GetByTitle("MDRDocuments");
    lblstatus.Text = " got the document library ";
    Excel.Application xlApp = new Excel.Application();
    Excel.Workbook xlWorkbook = xlApp.Workbooks.Open(@"D:/C.xlsx");
    Excel._Worksheet xlWorksheet = xlWorkbook.Sheets[1];
    Excel.Range xlRange = xlWorksheet.UsedRange;
    int rowCount = xlRange.Rows.Count;
    int colCount = xlRange.Columns.Count;
    for (int i = 1; i <= rowCount; i++)
    for (int j = 1; j <= colCount; j++)
    lblExcel.Text = xlRange.Cells[i, j].Value2.ToString();
     Error 1 at the above highlighted section of the code -  One or more types required to compile a dynamic expression cannot be found. Are you missing a reference? 
    Pallavi Sharma http://letsgetalittletechnical.blogspot.com/

    You might want to look at Excel Services and use the .../_vti_bin/ExcelRest.aspx
    http://msdn.microsoft.com/en-us/library/ee556820.ASPX
    This will allow an ajax call in the browser or web request to return Xml.  To ease access to content within Excel file setup Named Ranges.  http://development002/_vti_bin/ExcelRest.aspx/MDRDocuments/c.xlsx/model/Ranges('MyNamedRange')
    Hope this helps. 
    If looking to access Excel server-side use the OpenXML API, but avoid
    accessing the physical hard drive; put the Excel document in SharePoint.

  • Problem in reading from excel file with my requirement

    Hi,
    Below is my input excel file format
    A    XXX
    B    XXX
    C    XXX
    D    E   F   G  H  I    J  K  L  M  N
    XX   XX  XX  XX.........................XX
    All the A...N are headings and XX's are values.
    How should I define an internal table for this requirement. I am using FM TEXT_CONVERT_XLS_TO_SAP to read input file.
    Please let me know the correct way to define internal table for the above file format.
    Regards,
    Cheritha

    Hello Cheritha,
    Your final internal table(t_final) should have all the fields viz. A, B, C, D etc.
    You need to read the file to an internal table say t_data. In the internal table t_data, the field values will be each row in this internal table.
    So you need to loop on t_data and based on the field name assign it to the corresponding field in the internal table t_final.
    Hope this is clear if any clarification please do reply
    Regards
    Farzan

  • Error while uploading data to ztable from excel file

    Hi,
    I have a requirement where i have to upload data from excel file to ztable.I have used the fm 'ALSM_EXCEL_TO_INTERNAL_TABLE' for reading the excel file.After reading the excel file i have used INSERT zrb_hdr from table t_zrb_hdr for updating the ztable with data .
    here it is giving error as the data base table zrb_hdr and the internal table t_zrb_hdr should be declared of same type .
    I got this error b'coz i have changed the date and time fields in t_zrb_hdr table to char type.so the structure of zrb_hdr and t_zrb_hdr are not same.If i don't change the date and time fields,in the o/p i am not getting proper date and time formats.
    now how can i upload data into ztable?

    Hi,
    Try this.
    Data: itab type standard table of ztable,
             wa_itab type ztable.
    loop at t_zrb_hdr into wa_t_zrb_hdr.
       wa_itab-date = wa_t_zrb_hdr-date.
       wa_itab-time = wa_t_zrb_hdr-time.
       like  move all the fiedl to wa_itab...........
       append itab with wa_itab.
    Endloop.
    now insert the records from itab to the database table ztable.
    Thanks,
    Muthu.

  • How to best format input read from a file to a string

    I am trying to set up a class to convert input read from an xml-file to a java-string, which I can pass on to a web service.
    My attempt is probably not the smartest, but what I did was to set up a for-loop, which iterates through each line in the xml, appending "\n" to the end of each line, before storing them in a variable, which is loaded into an arraylist. When there are no more lines to read in the xml-file, the for-loop should terminate and the contents of the ArrayList should be written to a string, which is then returned.
    Below is my attempt to implement this - thanks in advance!
    import java.io.*;
    import java.util.*;
    public class RequestBuilder {
         private String _filename, output;
         //Constructor method
         RequestBuilder(String filename){
              String line;
              _filename = filename;
              //Sets up a array to store each line of XML read from a file
              ArrayList<String> lineList;
         lineList = new ArrayList<String>();
              try {
                   //Sets up a filereader and a buffer
                   FileReader fr = new FileReader(_filename);
                   BufferedReader br = new BufferedReader(fr);
                   //Iterates through each element of the arraylist until empty
                   for (String o : lineList){
                   //Stores a single linein a variable and appends a line-break
                   line = br.readLine() + "\n";
                   //Addseach line to the arraylist
                   lineList.add(line);
                   //Closes the filereader
                   fr.close();
                   //Writes the arraylist to a string
                   output = lineList.toString();
              } catch (FileNotFoundException e) {
                   e.printStackTrace();
              } catch (IOException e) {
                   e.printStackTrace();
         public String getRequest(){
              return output;
    }

    799992 wrote:
    Well, the reason for doing an ArrayList was that I had to process each line with line breaks and escape characters, but I know realize that I can do the same thing by summing the lines for each iteration directly intro a string like below - it works :-)
    Apparently the filereader takes care of double-quotes as I don't see any difference in the output when I disable the logic I made, which substitutes " with \", can anyone confirm this?
    The code I ended up using:
         //Sets up a filereader and a buffer
                   FileReader fr = new FileReader(_filename);
                   BufferedReader br = new BufferedReader(fr); 
                   //initializes the output variable with the first line from the file
                   output = br.readLine() + "\n";
                   while (br.ready() == true) {
                        //reads each line, saves it in a variable and appends line breaks
                        line = br.readLine() + "\n";
                        //Replaces adds escape character to any double-quotes (apparently not neccessary?)
                        tmpLine = line.replaceAll("\"", "\\\"");
                        line = tmpLine;
                        //sums each line in the current string
                        output = output + line;
    As EJP said you can directly write to the webservice. If you want to check for yourself what the result looks like just read the file without adding anything.
    public String readFile(){
         String xmlString = "";
              try{
                   String line = null;
                   xmlFile = new File(//file);
                   reader = new BufferedReader(new FileReader(xmlFile));
                        while((line = reader.readLine()) != null){
                             xmlString += line;
              catch(FileNotFoundException e){
                        e.printStackTrace();
              catch(IOException e){
                        e.printStackTrace();
         return xmlString.replaceAll("\\s+"," ").trim();//remove spaces
    }

  • How to read the data from Excel file and Store in XML file using java

    Hi All,
    I got a problem with Excel file.
    My problem is how to read the data from Excel file and Store in XML file using java excel api.
    For getting the data from Excel file what are all the steps i need to follow to get the correct result.
    Any body can send me the code (with java code ,Excel sheet) to this mail id : [email protected]
    Thanks & Regards,
    Sreenu,
    [email protected],
    india,

    If you want someone to do your work, please have the courtesy to provide payment.
    http://www.rentacoder.com

  • Read data from Excel file and diaplay in Webdynpro

    Hi all,
    I need some help. I have a Excel file with set of  name, phonenumbers . I want to know how to display the data using Webdynpro. Could some one help me. help is appreciated and I promise to award points for right answer.
    Thank you
    Maruti

    <b>Hi
    i can explain you to read data from Excel file
    First You have to download the jxl.jar file. You can get this file from the Below site
    </b><a href="http://www.andykhan.com/jexcelapi/download.html">jexcelapi jar</a>
    It will be in Compressed Fromat So Unzip it to get the Contents
    After Unzipping The File You will get a Folder (jexcelapi/jxl.jar)
    Now in NWDS open web dynpro explorer, Right Click Your Project, a popup menu will appear and in that click Properties
    You will get window displaying your Project Properties
    On Left Side of the window You Will Find "Java Build Path"
    Click That "Java Build Path" and you will get 4 Tabs Showing ( Source,Projects,Libraries,Order and Export)
    Click Libraries Tab
    You will find options many options buttons
    In that click the Button "Add External Jars"
    You will get Window in order to fecth the jxl.jar file from the location you had stored
    After selecting the jxl.jar i will get displayed and click ok
    Now Open Navigator
    Open Your Project
    You will find Lib folder
    Copy the jxl.jar to that lib folder
    Note : You cannot Read the Content from the excel file directly
    First You Have to copy that file to the Server,
    And from the Server you can get the file absolute path
    With the absolute path you can read the contents of the Excel file
    You have to save the Excel file as .xls Format and Not as xlsx format i will not accept that...
    You have Upload the Excel file from the Server Using the File Upload UI Element
    This Coding will extract 3 columns from the Xls File
    Coding
    import java.io.File;
    import java.io.FileOutputStream;
    import java.io.InputStream;
    import jxl.Cell;
    import jxl.Sheet;
    import jxl.Workbook;
    import com.sap.fileupload.wdp.IPrivateFileUpload_View;
    import com.sap.tc.webdynpro.services.sal.datatransport.api.IWDResource;
    public void onActionUpload_File(com.sap.tc.webdynpro.progmodel.api.IWDCustomEvent wdEvent )
        //@@begin onActionUpload_File(ServerEvent)
        IPrivateFileUpload_View.IContextElement element1 = wdContext.currentContextElement();
        IWDResource resource = element1.getFileResource();
        element1.setFileName(resource.getResourceName());
        element1.setFileExtension(resource.getResourceType().getFileExtension());
        //@@end
    public void onActionUpload_File_in_Server(com.sap.tc.webdynpro.progmodel.api.IWDCustomEvent wdEvent )
        //@@begin onActionUpload_File_in_Server(ServerEvent)
        InputStream text=null;
        int temp=0;
        try
             File file = new File(wdContext.currentContextElement().getFileResource().getResourceName().toString());
             FileOutputStream op = new FileOutputStream(file);
             if(wdContext.currentContextElement().getFileResource()!=null)
                  text=wdContext.currentContextElement().getFileResource().read(false);
                  while((temp=text.read())!=-1)
                       op.write(temp);                                      
             op.flush();
             op.close();
             path = file.getAbsolutePath();
             wdComponentAPI.getMessageManager().reportSuccess(path);
        catch(Exception e)
             e.printStackTrace();
        //@@end
    public void onActionUpload_Data_into_Table(com.sap.tc.webdynpro.progmodel.api.IWDCustomEvent wdEvent )
        //@@begin onActionUpload_Data_into_Table(ServerEvent)
        try
              Workbook wb =Workbook.getWorkbook(new File(path));
              Sheet sh = wb.getSheet(0);
              //wdComponentAPI.getMessageManager().reportSuccess("Columns = "+sh.getColumns());
              //wdComponentAPI.getMessageManager().reportSuccess("Rows = "+sh.getRows());
              int columns = sh.getColumns();
              int rows = sh.getRows();
              int i=0;
             for(int j=1;j<=rows;j++)
                       ele=wdContext.nodeTable_Data().createTable_DataElement();
                       Cell c1 = sh.getCell(i,j);
                      ele.setTab_Name(c1.getContents());
                       Cell c2 = sh.getCell(i+1,j);
                       ele.setTab_Degree(c2.getContents());
                          Cell c3 = sh.getCell(i+2,j);
                       ele.setTab_Percentage(c3.getContents());
                       wdContext.nodeTable_Data().addElement(ele);
        catch(Exception ex)
             wdComponentAPI.getMessageManager().reportSuccess(ex.toString());
        //@@end
       * The following code section can be used for any Java code that is
       * not to be visible to other controllers/views or that contains constructs
       * currently not supported directly by Web Dynpro (such as inner classes or
       * member variables etc.). </p>
       * Note: The content of this section is in no way managed/controlled
       * by the Web Dynpro Designtime or the Web Dynpro Runtime.
      //@@begin others
      String path;
      IPrivateFileUpload_View.ITable_DataElement ele;
    //@@end
    Regards
    Chandran S

Maybe you are looking for

  • How do I use Adaptive Limiter to make sure bounces are same volume?

    Hi, I've been making ear training exercises for myself - you can understand what here: http://discussions.apple.com/thread.jspa?threadID=490846&tstart=0 Here's what I need to do - and don't know how: I want all bounced exercises to play at the same v

  • Loops grayed out

    Earlier today all my loops categories were showing and able to use - shaker, piano, strings, etc. I downloaded the extras from the Apple web site and they were all working fine. I'd hit reset and they'd all show up. Now everything after the 4th categ

  • FSCM-COL:  Functional logic of Basic Rule BR00000002

    Hi, We are implementing SAP Collections Management and we have a few customers that are never considered valid to the Worklist. We checked a few customers and it seems that because of Basic Rule BR00000002 they aren't considered valid. I checked tran

  • Problem while deploying entity beans

    Hi, We are using JDeveloper 3.2.2 (NT) and 8.1.7 (NT) to deploy EJB's. Now we are trying to deploy the entity bean to Oracle JVM. We are facing the following problem while deploying an entity bean . "Persistence provider declared in the deployment de

  • Problem with serial read and write-unab​le to refresh the port number

    I use the advanced serail write and read example. Build the application, copy the application to another laptop with labview run time engine 2009 installed. And I connect my serial device via a serial to usb adaptor. The problem is that VISA source n