将sql查询结果导出到csv或excel

问题描述 投票:11回答:9

我想将sql查询的结果写入csv或excel文件,并将其保存在特定的文件夹中。我想知道是否可以使用java程序实现,可以重用任何sql查询结果。我会还想知道这是否可以用于不同类型的数据库(oracle,mysql,MS sql server等)。我打算将保存的文件附加到电子邮件中(这可能直接将sql查询结果导出到电子邮件中)。请帮忙。

java sql excel csv
9个回答
9
投票

使用openCSV API,您可以在csv文件中导出数据。

CSVWriter writer = new CSVWriter(new FileWriter("yourfile.csv"), '\t');
Boolean includeHeaders = true;

java.sql.ResultSet myResultSet = .... //your resultset logic here

writer.writeAll(myResultSet, includeHeaders);

writer.close();

3
投票

最简单的解决方案

主要方法

 private List<String> resultSetArray=new ArrayList<>();
 private String username ="";     // Enter DB Username
 private String password = "";    // Enter DB password
 private String url = "";         // Enter DB URL

 Connection connection=DriverManager.getConnection(url,user,pwd);   

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

        fetchDataFromDatabase("SQL queries", connection);
        printToCsv(resultArray);                

 }

从数据库中获取数据

下面的代码计算表中的列数,并存储在结果数组中。

private void fetchDataFromDatabase(String selectQuery,Connection connection) throws  Exception{
            try {


                Statement stmt = connection.createStatement();
                ResultSet rs = stmt.executeQuery(selectQuery);
                int numCols = rs.getMetaData().getColumnCount();

                while(rs.next()) {
                    StringBuilder sb = new StringBuilder();

                    for (int i = 1; i <= numCols; i++) {
                        sb.append(String.format(String.valueOf(rs.getString(i))) + " ");

                    }
                    resultSetArray.add(sb.toString());

                }

            } catch (SQLException e) {
                LOGGER.error("Sql exception " + e.getMessage());
            }

        }

printToCsv

 public static void printToCsv(List<String> resultArray) throws Exception{

        File csvOutputFile = new File(file_name);
        FileWriter fileWriter = new FileWriter(csvOutputFile, false);


        for(String mapping : resultArray) {
            fileWriter.write(mapping + "\n");
         }

        fileWriter.close();

    }

2
投票

这是一个例子:

import java.io.*;
import java.sql.*;
import org.apache.poi.hssf.usermodel.HSSFSheet;
import org.apache.poi.hssf.usermodel.HSSFWorkbook;
import org.apache.poi.hssf.usermodel.HSSFRow;
import org.apache.poi.hssf.usermodel.HSSFCell;

public class ExcelFile {
        public static void main(String[] args) {
                try {
                        Class.forName("com.mysql.jdbc.Driver").newInstance();
                        Connection connection = DriverManager.getConnection(
                                        "jdbc:mysql://localhost:3306/test", "root", "root");
                        PreparedStatement psmnt = null;
                        Statement st = connection.createStatement();
                        ResultSet rs = st.executeQuery("Select * from student");

                        HSSFWorkbook wb = new HSSFWorkbook();
                        HSSFSheet sheet = wb.createSheet("Excel Sheet");
                        HSSFRow rowhead = sheet.createRow((short) 0);
                        rowhead.createCell((short) 0).setCellValue("Roll No");
                        rowhead.createCell((short) 1).setCellValue("Name");
                        rowhead.createCell((short) 2).setCellValue("Class");
                        rowhead.createCell((short) 3).setCellValue("Marks");
                        rowhead.createCell((short) 4).setCellValue("Grade");

                        int index = 1;
                        while (rs.next()) {

                                HSSFRow row = sheet.createRow((short) index);
                                row.createCell((short) 0).setCellValue(rs.getInt(1));
                                row.createCell((short) 1).setCellValue(rs.getString(2));
                                row.createCell((short) 2).setCellValue(rs.getString(3));
                                row.createCell((short) 3).setCellValue(rs.getInt(4));
                                row.createCell((short) 4).setCellValue(rs.getString(5));
                                index++;
                        }
                        FileOutputStream fileOut = new FileOutputStream("c:\\excelFile.xls");
                        wb.write(fileOut);
                        fileOut.close();
                        System.out.println("Data is saved in excel file.");
                        rs.close();
                        connection.close();
                } catch (Exception e) {
                }
        }
}

Reference


2
投票

这是我的解决方案。要在主类中插入的代码:

import java.io.*;
import java.sql.*;
import com.company.*;
/**
 * Created by MAXNIGELNEGRO
*/
  String[] filePath =       new String[] {"C:\\Users\\Documents\\MyFile.csv"};
  String[] driverDB =       new String[] {"oracle.jdbc.driver.OracleDriver"};
  String[] stringConnDB =   new String[] {"jdbc:oracle:thin:@//127.0.0.1:1881/mydb"};
  String[] userDB =         new String[] {"pippo"};
  String[] passDB =         new String[] {"pluto"};
  String[] charSep =        new String[] {";"};
  Boolean colomn=   new Boolean (true);
  String[] queryDB =        new String[] {"select * FROM MYQUERY"};


try{
    System.out.println("---------------File exist?------------" + filePath[0]);
    File fileTemp = new File(filePath[0].toString());
    if (fileTemp.exists()){ 
        fileTemp.delete();
        System.out.println("---------------DELETE FILE------------" + filePath[0] );
                } 
   System.out.println("QUERY: ---->"+ queryDB[0].toString());
   exportQueryToCsv exp = new exportQueryToCsv();
   exp.exportQueryToCsv(filePath,driverDB,stringConnDB,userDB,passDB,queryDB, colomn,charSep);
   if (fileTemp.exists()){ 
     System.out.println("---File created---" + filePath[0]);
  }

}
catch(Exception e){
         e.printStackTrace();
      }

核心课程:

import java.io.IOException;
import java.sql.Connection;
import java.sql.ResultSet;
import java.sql.SQLException;
import java.sql.Statement;

/**
 * Created by MAXNIGELNEGRO
 */
public class exportQueryToCsv {
    public exportQueryToCsv(){}
    public static void  exportQueryToCsv (String[] filename, String[] driverDB, String[] connDB
                                            , String[] userDB, String[] passDB, String[] queryDB, Boolean intestaFile
                                            , String[] charSep) throws SQLException, IOException {
        Statement stmt=null;
        ResultSet rset=null;
        Connection conn=null;
        try { DBConn connessione = new DBConn();
        conn=connessione.connect(driverDB[0],connDB[0],userDB[0],passDB[0]);
        conn.setAutoCommit(false);

        stmt = conn.createStatement();

        rset = stmt.executeQuery(queryDB[0]);

        ExportData2CSV csv = new ExportData2CSV();
        csv.ExportData2CSV(rset,filename[0],intestaFile,charSep[0]);

            csv.createFileCsv();
        } catch (SQLException e) {
                e.printStackTrace();
        } catch (IOException e) {
                e.printStackTrace();
        }
        finally {
            if (stmt != null) {stmt.close();}
            if (conn != null) {conn.close();}
            if (rset != null) {rset.close();}



        }


    }
}

这是用于连接数据库的类DBConn

import java.sql.*;

/**
 * Created by MAXNIGELNEGRO
 */
public class DBConn {
    public DBConn() {
    }
    public Connection connect(String driverDB, String db_connect_str, String db_userid, String db_password) {
        Connection conn;

        try {
            Class.forName(driverDB).newInstance();
            conn = DriverManager.getConnection(db_connect_str, db_userid, db_password);


        } catch (Exception e) {
            e.printStackTrace();
            conn = null;

        }
        return conn;
    }


}

这是用于从表到结果集检索数据并写入csv文件的类

package com.company;

import java.io.FileWriter;
import java.io.IOException;
import java.sql.ResultSet;
import java.sql.ResultSetMetaData;
import java.sql.SQLException;

/**
 * Created by MAXNIGELNEGRO 
 */
public class ExportData2CSV {
    public ResultSet rset;
    public String filename;
    public Boolean colomnName;
    public String charSep;

    public void ExportData2CSV(ResultSet rset, String filename, Boolean colomnName, String charSep) {
        this.rset = rset;
        this.filename = filename;
        this.colomnName = colomnName;
        this.charSep = charSep;
    }

    public void createFileCsv() throws SQLException, IOException {
        FileWriter cname = null;
        try {

                // WRITE COLOMN NAME
            ResultSetMetaData rsmd = rset.getMetaData();
            cname = new FileWriter(filename);
            if (colomnName) {
                for (int i = 1; i <= rsmd.getColumnCount(); i++) {
                    cname.append(rsmd.getColumnName(i));
                    cname.append(charSep);
                    cname.flush();
                }
                cname.append(System.getProperty("line.separator"));
            }

            // WRITE DATA
            while (rset.next()) {
                for (int i = 1; i <= rsmd.getColumnCount(); i++) {
                    if (rset.getObject(i) != null) {
                        String data = rset.getObject(i).toString().replaceAll(charSep, "");
                        cname.append(data);
                        cname.append(charSep);
                    } else {
                        String data = "null";
                        cname.append(data);
                        cname.append(charSep);
                    }

                }
                //new line entered after each row
                cname.append(System.getProperty("line.separator"));

            }


        } catch (Exception e) {
            e.printStackTrace();

        } finally {
            if (cname != null) {
                cname.flush();
                cname.close();
            }
            if (rset != null) {
                rset.close();
            }

        }

    }
}

1
投票

是!

您可以使用jdbc连接到不同的数据库类型,然后使用结果(Seen here)创建Excel。

import java.sql.Connection;
import java.sql.DriverManager;
import java.sql.ResultSet;
import java.sql.SQLException;
import java.sql.Statement;

public class TestAccessExcel {
  public static Connection getConnection() throws Exception {
    String driver = "sun.jdbc.odbc.JdbcOdbcDriver";
    String url = "jdbc:odbc:excelDB";
    String username = "username";
    String password = "pass";
    Class.forName(driver);
    return DriverManager.getConnection(url, username, password);
  }

  public static void main(String args[]) {
    Connection conn = null;
    Statement stmt = null;
    ResultSet rs = null;
    try {
      conn = getConnection();
      stmt = conn.createStatement();
      String excelQuery = "select * from [Sheet1$]";
      rs = stmt.executeQuery(excelQuery);

      while (rs.next()) {
        System.out.println(rs.getString("BadgeNumber") + " " + rs.getString("FirstName") + " "
            + rs.getString("LastName"));
      }
    } catch (Exception e) {
      System.err.println(e.getMessage());
    } finally {
      try {
        rs.close();
        stmt.close();
        conn.close();

      } catch (SQLException e) {
        e.printStackTrace();
      }
    }
  }
}

1
投票

这是excel数据表

input excel file containing records嗨这是你需要3个文件的解决方案1.input thread 2.output thread 3.data structure 4.main 1.input thread to read excel和output thread to write sql out put 2.data structure is to hold and传输数据

(input thread.Java)

    import java.io.*; 
public class InputThread extends Thread{


    String fp; 
    InputString is; 
    String tableName="emp"; 
    String outFile;
    InputThread(String FilePath,String nameOfTheTable,String outFileName){
        fp=FilePath;
        outFile=outFileName;
        tableName=nameOfTheTable;
    }
    public void run(){
        File file = new File(fp);
        String line;
        try{
            BufferedReader br = new BufferedReader(new FileReader(file)); 
            if( (line=br.readLine()) != null)
                is = new InputString(line);

            //transform(is);    

            InputString tmp = new InputString(createTable(line));
            //tmp.next = is;
            is = tmp;
            //tmp = tmp.next;

            for(; (line = br.readLine()) != null; ) {
                tmp.next = new InputString(line);
                tmp = tmp.next;
                transform(tmp); 
                }               

        }catch(Exception e){ System.out.println("Error is :"+e); }

        //traverse();
        new OutputThread(is,outFile).start();
    }
    void transform(InputString x){

        String[] arr = x.getLine().split(",");
        String sql = "insert into "+tableName+" values(";
        for(int i=0;i<arr.length;i++){
            sql+="'"+arr[i]+"'";
            if( (i+1) < arr.length) sql+=",";
        }
        sql+=");";
        x.setLine(sql);

    }
    String createTable(String x){
        String[] arr = x.split(",");
        String sql = "create database vamsidb "+ "use vamsidb "+"create table "+tableName+"(";
        for(int i=0;i<arr.length;i++){
            sql+=arr[i]+" varchar(50)";
            if( (i+1) < arr.length) sql+=",";
        }
        sql+=");";
        return sql;
    }
    /*public void traverse(){
        InputString tmp = is;
        while(is != null){
            System.out.println(is.getLine());
            is=is.next;
        }
    }*/


}

(output thread.Java)

import java.io.*;
public class OutputThread extends Thread{
    InputString is;
    String outFile;
    OutputThread(InputString linkedList,String outFileName){
        is=linkedList;
        outFile = outFileName;
    }
    public void run(){

        try{
            FileOutputStream fos = new FileOutputStream(outFile);
            while(is != null){              
                fos.write(is.getLine().getBytes());             
                is=is.next;
            }
            fos.close();
        }catch(Exception e){
            System.out.println("Error is :"+e);
         }
    }
}

(main.Java)

public class Main{
public static void main(String[] args){

        InputThread it = new InputThread("sasken.csv","emp","output.sql");

        it.start();     
    }
}

(data structure.Java)

//此类表示要将输入//数据保存和转换为sql语句的链接列表的数据结构

class InputString{

    String line;
    InputString next;

    InputString(String x){
        line = x;
    }
    String getLine(){
        return line;
    }   
    void setLine(String x){
        line = x;
    }
}

output result


0
投票

为此,您需要编写一个可以占用任何查询和任何驱动程序的小代码。第一个输入应该是驱动程序名称作为您正在编写的软件的输入。然后,您正在编写的软件应该可以执行任何给定的SQL,并只提供行和列。

下一个任务是解析来自Java应用程序的JDBC的ResultSet。您要么将结果写入CSV文件,要么EXCEL基于您拥有java api的优势。

将输出写入CVS很容易,而不是简单。我还没有将数据导出到Excel中。我相信你会找到罐子。


0
投票

从任何工具导出结果集数据都很困难。

例如:在将结果集数据导出到.csv文件时,当数据包含(,)时,它无法正确导出

请参考下面的java代码:

它可以与任何查询输入和结果集中的所有类型的数据完美配合

package com.demo.export;

import java.io.FileInputStream;
import java.io.FileOutputStream;
import java.sql.Connection;
import java.sql.ResultSet;
import java.sql.ResultSetMetaData;
import java.sql.SQLException;
import java.sql.Statement;

import org.apache.poi.hssf.usermodel.HSSFWorkbook;
import org.apache.poi.ss.usermodel.Cell;
import org.apache.poi.ss.usermodel.Row;
import org.apache.poi.ss.usermodel.Sheet;
import org.apache.poi.ss.usermodel.Workbook;
import org.apache.poi.ss.usermodel.WorkbookFactory;

public class dataExportService {
    public void getDefendants(Connection con , String db) throws Exception  { 
        @SuppressWarnings("unused")
        Workbook readWorkbook = WorkbookFactory.create(new FileInputStream(".xls file path(C:\\Users\\CEPL\\Desktop\\test.xls)") );
        @SuppressWarnings("resource")
        Workbook writeWorkbook = new HSSFWorkbook();
        Sheet desSheet = writeWorkbook.createSheet("new sheet");

        Statement stmt = null;
        ResultSet rs = null;
        try{
            String query ="QUERY";

            stmt = con.createStatement();
            rs = stmt.executeQuery(query);
            ResultSetMetaData rsmd = rs.getMetaData();
            int columnsNumber = rsmd.getColumnCount();

            Row desRow1 = desSheet.createRow(0);
            for(int col=0 ;col < columnsNumber;col++) {
                Cell newpath = desRow1.createCell(col);
                newpath.setCellValue(rsmd.getColumnLabel(col+1));
            }
            while(rs.next()) {
                System.out.println("Row number" + rs.getRow() );
                Row desRow = desSheet.createRow(rs.getRow());
                for(int col=0 ;col < columnsNumber;col++) {
                    Cell newpath = desRow.createCell(col);
                    newpath.setCellValue(rs.getString(col+1));  
                }
                FileOutputStream fileOut = new FileOutputStream(".xls file path(C:\\Users\\CEPL\\Desktop\\test.xls)");
                writeWorkbook.write(fileOut);
                fileOut.close();
            }
        }
        catch (SQLException e) {
            System.out.println("Failed to get data from database");
        }
    }

}

0
投票

您可以使用JDBC从java中的DB获取记录,然后使用Apache POI将数据导出到CSV / Excel。

此外,您可以使用java的桌面API使用默认电子邮件客户端发送电子邮件。

© www.soinside.com 2019 - 2024. All rights reserved.