0

我用java制作了一个程序,它需要一个excel文件并将其数据存储在数据库中。当我说明文件在哪里时,它是这样的:

String filename = "test5.xls";

        String path = "C:\\Users\\myfiles\\Documents\\";

但是当我调用创建表并声明excel文件的文件名时,因为它是test.xls,mysql命令显示错误!创建表函数为:

try
            {
                String all = org.apache.commons.lang3.StringUtils.join(allFields, ",");
                String createTableStr = "CREATE TABLE " + "table5" + " (" + all + ")";

                System.out.println( "Create a new table in the database" );
                stmt.executeUpdate( createTableStr );

有没有办法在我创建表之前重命名文件或只读取没有.xls的“测试”?我的程序如下:

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 readexcel {

    public static void main (String[] args) throws Exception {

        //String filename = "C:\\Users\\myfiles\\Documents\\test5.xls";
        String filename = "test5.xls";
        String path = "C:\\Users\\myfiles\\Documents\\";

        List sheetData = new ArrayList();
        FileInputStream fis = null;
        try {
            fis = new FileInputStream(path + 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);
    HashMap<String,Integer> tFields = new HashMap();
    tFields = parseExcelData(sheetData);
    String str = getCreateTable(filename, tFields);

    }

    private static void showExcelData(List sheetData) {
//      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(", ");
              }
          }
          System.out.println("");
        }
    }


    @SuppressWarnings({ "unchecked", "unused" })
    private static 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;

        }

    private static 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;
        }
        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 all = org.apache.commons.lang3.StringUtils.join(allFields, ",");
                String createTableStr = "CREATE TABLE " + "table5.xls" + " (" + all + ")";

                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 str; 
    }

    @SuppressWarnings({ "unused", "unused", "unused", "unused" })
    private Statement createStatement() {
        return null;
    }

}

先感谢您!

4

1 回答 1

0

给出文件名

String filename = "test5.xls";
String path = "C:\\Users\\myfiles\\Documents\\";

File f = new File (path + filename);
System.out.println(f.getName());// gives only file name with out extension
于 2013-04-19T07:06:51.713 回答