Tôi muốn ghi kết quả của truy vấn sql vào tệp csv hoặc excel và lưu nó vào một thư mục cụ thể. Tôi muốn biết điều này có thể đạt được bằng cách sử dụng chương trình java hay không có thể được tái sử dụng cho bất kỳ kết quả truy vấn sql nào. Tôi cũng muốn biết nếu điều này có thể được sử dụng cho các loại cơ sở dữ liệu khác nhau (oracle, mysql, MS sql server etc) .Tôi định đính kèm tệp đã lưu vào email (là có thể trực tiếp xuất kết quả truy vấn sql sang email) .Xin vui lòng trợ giúp.xuất kết quả truy vấn sql sang csv hoặc excel
Trả lời
Dưới đây là một ví dụ:
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) {
}
}
}
Có!
Bạn có thể kết nối với các loại cơ sở dữ liệu khác nhau bằng cách sử dụng jdbc và sau đó tạo một Excel với kết quả (Seen here).
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();
}
}
}
}
Đây là một cách thực sự khéo léo để xử lý nó nếu bạn đang ở trong một môi trường Windows. Ngoài ra nó là tương đối "di động" trong đó ý tưởng tương tự làm việc với bất kỳ ngôn ngữ. Thay thế Apache cũng không phải là một ý tưởng tồi. –
Ví dụ này cho thấy cách đọc từ bảng tính excel, không phải cách tạo bảng tính. – datguy
Để làm việc này, bạn cần viết một mã nhỏ có thể chiếm bất kỳ truy vấn và trình điều khiển nào. Đầu vào đầu tiên phải là tên trình điều khiển làm đầu vào cho phần mềm mà bạn đang viết. Sau đó, phần mềm bạn đang viết phải ở trong một vị trí để thực hiện bất kỳ SQL nào được cung cấp cho nó và chỉ đưa ra các hàng và cột.
Nhiệm vụ tiếp theo là phân tích cú pháp ResultSet đến từ JDBC của ứng dụng java. Hoặc bạn muốn viết kết quả vào tệp CSV hoặc EXCEL dựa trên mức độ bạn có java api để thực hiện điều đó.
Viết đầu ra vào CVS dễ dàng và không phải là trival. Tôi đã không làm việc để xuất dữ liệu vào Excel. Tôi chắc chắn bạn tìm thấy lọ cho điều đó.
Đây là giải pháp của tôi. Mã để chèn vào những lớp học chính:
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();
}
Lớp lõi:
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();}
}
}
}
Đây là lớp DBConn cho kết nối tới cơ sở dữ liệu
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;
}
}
Đây là lớp học cho lấy dữ liệu từ bảng để ResultSet và ghi vào tập tin 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();
}
}
}
}
Với việc sử dụng của openCSV API, bạn có thể xuất dữ liệu của bạn trong tập tin 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();
Đây là bảng dữ liệu excel
input excel file containing records Hi đây là giải pháp bạn cần 3 file 1.input chủ đề cấu trúc đề 2.output 3.data 4.main 1.input thread để đọc excel và đầu ra thread để viết sql ra đặt 2. cấu trúc dữ liệu là để giữ và chuyển dữ liệu
(InputThread.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;
}
}*/
}
(OutputThread.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();
}
}
(DataStructure.java)
// Lớp này đại diện cho cấu trúc dữ liệu giữ và chuyển đổi dữ liệu nhập // dưới dạng danh sách các câu lệnh sql được liên kết
class InputString{
String line;
InputString next;
InputString(String x){
line = x;
}
String getLine(){
return line;
}
void setLine(String x){
line = x;
}
}
giải pháp đơn giản nhất.
Main Method
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);
}
fetchDataFromDatabase
Đoạn code dưới đây đếm số lượng các cột trong một bảng, và lưu trữ trong một mảng kết quả.
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();
}
- 1. Xuất Javascript hoặc Flash sang CSV/Excel
- 2. Xuất dữ liệu truy vấn SQL sang Excel
- 3. Xuất sang csv - LINQ truy vấn
- 4. Xuất kết quả truy vấn JasperReports
- 5. Xuất SQL sang Excel
- 6. Dữ liệu SilverlightGrid: Xuất sang excel hoặc csv
- 7. Oracle cách xuất truy vấn sang tệp văn bản/csv
- 8. SQLite3 (hoặc SQL chung) truy xuất hàng thứ n của kết quả truy vấn
- 9. Kết quả truy vấn SQL trong một chuỗi (hoặc biến)
- 10. Cách gửi kết quả truy vấn ở định dạng CSV?
- 11. Xuất từ lợn sang CSV
- 12. Xuất từ SQL Server sang Excel với tiêu đề cột?
- 13. kết quả truy vấn xuất dưới dạng CSV thông qua PHP
- 14. Chuyển đổi kết quả truy vấn LINQ sang từ điển
- 15. xuất sang csv wordpress
- 16. Truy vấn MY-SQL để xuất dữ liệu trong tệp excel
- 17. Thêm cột vào kết quả truy vấn SQL
- 18. Kết quả truy vấn nhóm SQL cho một cột đơn
- 19. Giới hạn kết quả truy vấn SQL trong MySQL
- 20. Cách xuất truy vấn SQL sang TXT bằng cách sử dụng dòng lệnh
- 21. php + jqgrid + xuất sang excel
- 22. SQL - "Lưu kết quả dưới dạng CSV" - sử dụng dấu phẩy thay vì Bán đại tràng
- 23. Sử dụng VBA để xuất tất cả truy vấn MS Access SQL sang tệp văn bản
- 24. Xuất từ PHP sang Excel
- 25. Xuất DataTable sang Excel File
- 26. Kết quả truy vấn Oracle mâu thuẫn
- 27. SQL - Kết hợp nhiều truy vấn như truy vấn
- 28. Mô hình Django truy xuất cùng một kết quả
- 29. Đặt kết quả biến, từ truy vấn
- 30. Thứ tự kết quả truy vấn XPath
Đây là chính xác những gì bạn đang tìm kiếm: https://www.youtube.com/watch?v=hlY_PoJhlMk (https://mvnrepository.com/ artifact/net.sf.automatic-report-generator) –