Java读取Excel文件,生成SQL语句

import jxl.Sheet;
import jxl.Workbook;
import jxl.read.biff.BiffException;

import java.io.*;

public class Main {
    public static void main(String[] args) {
        Main obj = new Main();
        File file = new File("D:\\工作表1.xls");
        obj.readExcel(file);
    }

    // 去读Excel的方法readExcel,该方法的入口参数为一个File对象
    public void readExcel(File file) {
        try {
            // 创建输入流,读取Excel
            InputStream is = new FileInputStream(file.getAbsolutePath());
            // jxl提供的Workbook类
            Workbook wb = Workbook.getWorkbook(is);
            // Excel的页签数量
            int sheet_size = wb.getNumberOfSheets();
            for (int index = 0; index < sheet_size; index++) {
                // 每个页签创建一个Sheet对象
                Sheet sheet = wb.getSheet(index);
                // sheet.getRows()返回该页的总行数
                StringBuilder sb = new StringBuilder();
                String str1 = "";
                String str2 = "";
                String str3 = "";
                int count = 0;
                for (int i = 0; i < sheet.getColumns(); i++) {
                    // sheet.getColumns()返回该页的总列数
                    ++count;
                    for (int j = 0; j < sheet.getRows(); j++) {
                        String cellinfo = sheet.getCell(i, j).getContents();
                        if (j == 0) {
                            str1 = cellinfo;
                        } else if (j == 1) {
                            str2 = cellinfo;
                        } else {
                            str3 = cellinfo;
                        }
                    }
                    sb.append(str1).append("  ").append(str3).append("  ").append("comment").append("'").append(str2).append("'").append(",");
                    System.out.println(sb.toString());
                    sb.setLength(0);
                    str1 = "";
                    str2 = "";
                    str3 = "";
                }
                System.out.println("总字段数:"+count);
            }
        } catch (FileNotFoundException e) {
            e.printStackTrace();
        } catch (BiffException e) {
            e.printStackTrace();
        } catch (IOException e) {
            e.printStackTrace();
        }
    }
}

//id  int  comment'主键id',
//name  varchar  comment'姓名',
//age  int  comment'年龄',
//总字段数:3
//总字段数:0
//总字段数:0


Java读取Excel文件,生成SQL语句_第1张图片 Java读取Excel文件,生成SQL语句_第2张图片


注意;jxl只能解析.xls格式的表格


如果字段较多,可以直接生成SQL语句









你可能感兴趣的:(Java)