新聞中心
在數(shù)據(jù)庫(kù)管理中,數(shù)據(jù)的導(dǎo)入和導(dǎo)出是非常重要的一環(huán)。在實(shí)際操作中,往往需要將數(shù)據(jù)庫(kù)中的數(shù)據(jù)進(jìn)行導(dǎo)出,以備日后使用。對(duì)于Java程序員來(lái)說(shuō),如何實(shí)現(xiàn)數(shù)據(jù)庫(kù)數(shù)據(jù)的導(dǎo)出可能是一個(gè)問題。本文將會(huì)介紹如何使用Java編程實(shí)現(xiàn)數(shù)據(jù)庫(kù)數(shù)據(jù)的導(dǎo)出。

創(chuàng)新互聯(lián)專注于遜克企業(yè)網(wǎng)站建設(shè),自適應(yīng)網(wǎng)站建設(shè),商城網(wǎng)站定制開發(fā)。遜克網(wǎng)站建設(shè)公司,為遜克等地區(qū)提供建站服務(wù)。全流程按需求定制設(shè)計(jì),專業(yè)設(shè)計(jì),全程項(xiàng)目跟蹤,創(chuàng)新互聯(lián)專業(yè)和態(tài)度為您提供的服務(wù)
一、連接數(shù)據(jù)庫(kù)
在進(jìn)行數(shù)據(jù)庫(kù)數(shù)據(jù)的導(dǎo)出操作之前,首先需要建立數(shù)據(jù)庫(kù)連接,這需要使用JDBC技術(shù)。JDBC(Java Database Connectivity)是Java連接各種類型的關(guān)系數(shù)據(jù)庫(kù)的標(biāo)準(zhǔn)API,通過(guò)它可以實(shí)現(xiàn)與各種數(shù)據(jù)庫(kù)的連接、數(shù)據(jù)庫(kù)的操作。下面是連接MySQL數(shù)據(jù)庫(kù)的代碼:
“`java
public class DatabaseUtil {
private static Connection conn = null;
static {
// 數(shù)據(jù)庫(kù)連接配置參數(shù)
String url = “jdbc:mysql://localhost:3306/test”;
String user = “root”;
String password = “admin”;
try {
// 加載數(shù)據(jù)庫(kù)驅(qū)動(dòng)
Class.forName(“com.mysql.jdbc.Driver”);
// 建立數(shù)據(jù)庫(kù)連接
conn = DriverManager.getConnection(url, user, password);
} catch (ClassNotFoundException | SQLException e) {
e.printStackTrace();
}
}
// 獲取數(shù)據(jù)庫(kù)連接對(duì)象
public static Connection getConnection() {
return conn;
}
// 關(guān)閉數(shù)據(jù)庫(kù)連接
public static void close() {
if (conn != null) {
try {
conn.close();
} catch (SQLException e) {
e.printStackTrace();
}
}
}
}
“`
二、獲取數(shù)據(jù)庫(kù)數(shù)據(jù)
建立數(shù)據(jù)庫(kù)連接后,就可以開始獲取數(shù)據(jù)庫(kù)數(shù)據(jù)了。對(duì)于JDBC技術(shù),獲取數(shù)據(jù)可以采用PreparedStatement對(duì)象和ResultSet對(duì)象來(lái)實(shí)現(xiàn)。其中PreparedStatement用于執(zhí)行一個(gè)預(yù)定義的SQL語(yǔ)句,而ResultSet用于存放執(zhí)行結(jié)果。下面是獲取MySQL數(shù)據(jù)庫(kù)中的數(shù)據(jù)的代碼:
“`java
List> data = new ArrayList();
String sql = “SELECT * FROM test”;
PreparedStatement ps = conn.prepareStatement(sql);
ResultSet rs = ps.executeQuery();
ResultSetMetaData rd = rs.getMetaData();
int count = rd.getColumnCount();
while (rs.next()) {
Map rowData = new HashMap();
for (int i = 1; i
rowData.put(rd.getColumnName(i), rs.getObject(i));
}
data.add(rowData);
}
“`
在這里,獲取到的數(shù)據(jù)是一個(gè)List對(duì)象,每個(gè)元素是一個(gè)Map對(duì)象,Map對(duì)象用于存放一行數(shù)據(jù),其中,鍵是列的名稱,值是列的值。
三、將數(shù)據(jù)導(dǎo)出為Excel
經(jīng)過(guò)上面的步驟,我們已經(jīng)獲取到了數(shù)據(jù)庫(kù)中的數(shù)據(jù),下面就可以將數(shù)據(jù)導(dǎo)出成Excel格式的文件。Java中可以使用Apache POI庫(kù)來(lái)實(shí)現(xiàn)Excel文件的創(chuàng)建和編輯。需要注意的是,因?yàn)锳pache POI不支持直接在內(nèi)存中處理Excel文件,所以需要先創(chuàng)建臨時(shí)文件,將數(shù)據(jù)寫入臨時(shí)文件,最后再將臨時(shí)文件輸出到客戶端。
下面的代碼展示了如何將獲取到的數(shù)據(jù)導(dǎo)出成Excel文件:
“`java
public void exportToExcel(String fileName, List> data) {
HSSFWorkbook workbook = new HSSFWorkbook();
HSSFSheet sheet = workbook.createSheet(“Sheet1”);
// 設(shè)置表格列頭
HSSFRow headerRow = sheet.createRow(0);
Map headerData = data.get(0);
int cellIndex = 0;
for (String key : headerData.keySet()) {
headerRow.createCell(cellIndex++).setCellValue(key);
}
// 設(shè)置表格數(shù)據(jù)
int rowIndex = 1;
for (Map rowData : data) {
HSSFRow dataRow = sheet.createRow(rowIndex++);
cellIndex = 0;
for (String key : rowData.keySet()) {
Object value = rowData.get(key);
if (value instanceof String) {
dataRow.createCell(cellIndex++).setCellValue((String)value);
} else if (value instanceof Integer) {
dataRow.createCell(cellIndex++).setCellValue((int)value);
} else if (value instanceof Double) {
dataRow.createCell(cellIndex++).setCellValue((double)value);
}
}
}
try {
// 創(chuàng)建臨時(shí)文件
File tempFile= File.createTempFile(String.valueOf(System.currentTimeMillis()), “.xls”);
FileOutputStream fos = new FileOutputStream(tempFile);
workbook.write(fos);
fos.close();
// 輸出Excel文件到客戶端
response.reset();
response.setContentType(“application/vnd.ms-excel”);
response.setHeader(“Content-Disposition”, “attachment;filename=” + fileName + “.xls”);
FileInputStream fis = new FileInputStream(tempFile);
OutputStream os = response.getOutputStream();
byte[] bytes = new byte[1024];
int readLength;
while ((readLength = fis.read(bytes)) != -1) {
os.write(bytes, 0, readLength);
}
os.flush();
os.close();
fis.close();
// 刪除臨時(shí)文件
tempFile.delete();
} catch (IOException e) {
e.printStackTrace();
}
}
“`
四、完整代碼
將上述的代碼片段整合起來(lái),得到完整的Java代碼:
“`java
public class DataExportUtil {
private static final String DRIVER_CLASS = “com.mysql.jdbc.Driver”;
private static final String URL = “jdbc:mysql://localhost:3306/test”;
private static final String USER = “root”;
private static final String PASSWORD = “admin”;
public void export(String fileName, String tableName, HttpServletRequest request, HttpServletResponse response) {
Connection conn = null;
try {
Class.forName(DRIVER_CLASS);
conn = DriverManager.getConnection(URL, USER, PASSWORD);
List> data = new ArrayList();
String sql = “SELECT * FROM ” + tableName;
PreparedStatement ps = conn.prepareStatement(sql);
ResultSet rs = ps.executeQuery();
ResultSetMetaData rd = rs.getMetaData();
int count = rd.getColumnCount();
while (rs.next()) {
Map rowData = new HashMap();
for (int i = 1; i
rowData.put(rd.getColumnName(i), rs.getObject(i));
}
data.add(rowData);
}
HSSFWorkbook workbook = new HSSFWorkbook();
HSSFSheet sheet = workbook.createSheet(“Sheet1”);
// 設(shè)置表格列頭
HSSFRow headerRow = sheet.createRow(0);
Map headerData = data.get(0);
int cellIndex = 0;
for (String key : headerData.keySet()) {
headerRow.createCell(cellIndex++).setCellValue(key);
}
// 設(shè)置表格數(shù)據(jù)
int rowIndex = 1;
for (Map rowData : data) {
HSSFRow dataRow = sheet.createRow(rowIndex++);
cellIndex = 0;
for (String key : rowData.keySet()) {
Object value = rowData.get(key);
if (value instanceof String) {
dataRow.createCell(cellIndex++).setCellValue((String)value);
} else if (value instanceof Integer) {
dataRow.createCell(cellIndex++).setCellValue((int)value);
} else if (value instanceof Double) {
dataRow.createCell(cellIndex++).setCellValue((double)value);
}
}
}
// 創(chuàng)建臨時(shí)文件
File tempFile= File.createTempFile(String.valueOf(System.currentTimeMillis()), “.xls”);
FileOutputStream fos = new FileOutputStream(tempFile);
workbook.write(fos);
fos.close();
// 輸出Excel文件到客戶端
response.reset();
response.setContentType(“application/vnd.ms-excel”);
response.setHeader(“Content-Disposition”, “attachment;filename=” + fileName + “.xls”);
FileInputStream fis = new FileInputStream(tempFile);
OutputStream os = response.getOutputStream();
byte[] bytes = new byte[1024];
int readLength;
while ((readLength = fis.read(bytes)) != -1) {
os.write(bytes, 0, readLength);
}
os.flush();
os.close();
fis.close();
// 刪除臨時(shí)文件
tempFile.delete();
} catch (ClassNotFoundException | SQLException | IOException e) {
e.printStackTrace();
} finally {
if (conn != null) {
try {
conn.close();
} catch (SQLException e) {
e.printStackTrace();
}
}
}
}
}
“`
注:在使用時(shí),需要將DRIVER_CLASS、URL、USER、PASSWORD改為自己的數(shù)據(jù)庫(kù)連接信息。
五、
本文詳細(xì)介紹了如何使用Java編程實(shí)現(xiàn)數(shù)據(jù)庫(kù)數(shù)據(jù)的導(dǎo)出,并將數(shù)據(jù)導(dǎo)出成Excel文件格式。盡管代碼較長(zhǎng),但是只需要以下幾步即可完成導(dǎo)出操作:
1.建立數(shù)據(jù)庫(kù)連接
2.獲取數(shù)據(jù)庫(kù)數(shù)據(jù)
3.將數(shù)據(jù)導(dǎo)出成Excel文件
相關(guān)問題拓展閱讀:
- java中把SQL數(shù)據(jù)庫(kù)中的表導(dǎo)出到excel中.怎么實(shí)現(xiàn)
java中把SQL數(shù)據(jù)庫(kù)中的表導(dǎo)出到excel中.怎么實(shí)現(xiàn)
前段時(shí)間正好做了,導(dǎo)入和導(dǎo)出的,你自己看吧
/**導(dǎo)出數(shù)據(jù)為XLS格式
* @param fos
* @param bo
*/
public void writeExcelBo(FileOutputStream fos, java.util.Vector ve)
{
jxl.write.WritableWorkbook wwb;
try
{
wwb= Workbook.createWorkbook(fos);
jxl.write.WritableSheet ws= wwb.createSheet(“booksheet”, 10);
ws.addCell(new jxl.write.Label(0, 1, “書核備目ID”));
ws.addCell(new jxl.write.Label(1, 1, “ISBN”));
ws.addCell(new jxl.write.Label(2, 1, “定價(jià)”陸鉛));
ws.addCell(new jxl.write.Label(3, 1, “書名”));
ws.addCell(new jxl.write.Label(4, 1, “原書名”));
ws.addCell(new jxl.write.Label(5, 1, “副題名”));
ws.addCell(new jxl.write.Label(6, 1, “著者”));
ws.addCell(new jxl.write.Label(7, 1, “譯者”));
ws.addCell(new jxl.write.Label(8, 1, “版次”));
ws.addCell(new jxl.write.Label(9, 1, “出版地”));
ws.addCell(new jxl.write.Label(10, 1, “出版社”));
ws.addCell(new jxl.write.Label(11, 1, “出版日期”));
ws.addCell(new jxl.write.Label(12, 1, “頁(yè)數(shù)”));
ws.addCell(new jxl.write.Label(13, 1, “書高”));
ws.addCell(new jxl.write.Label(14, 1, “裝幀”));
ws.addCell(new jxl.write.Label(15, 1, “叢書名”));
ws.addCell(new jxl.write.Label(16, 1, “一般性附注項(xiàng)”));
ws.addCell(new jxl.write.Label(17, 1, “簡(jiǎn)介”));
ws.addCell(new jxl.write.Label(18, 1, “主題改悉毀詞”));
ws.addCell(new jxl.write.Label(19, 1, “中圖法分類”));
ws.addCell(new jxl.write.Label(20, 1, “更新日期”));
ws.addCell(new jxl.write.Label(21, 1, “本數(shù)”));
book=new Book;
for (int i= 0; i 0)
{
try
{
fis= new FileInputStream(f);
BookBean bob= new BookBean();
UserBean u= new UserBean();
jxl.Workbook rwb= Workbook.getWorkbook(fis);
jxl.Sheet sh= rwb.getSheet(0);
int rowCount= sh.getRows();
SimpleDateFormat sdf= new SimpleDateFormat(“dd/MM/yyyy”);
book= new Book;
for (int i= 1; i
{
book= new Book();
jxl.Cell ce= sh.getRow(i);
book.setIn(ce.getContents().toString());
book.setSeries(ce.getContents().toString());
book.setBookTitle(ce.getContents().toString());
book.setWriter(ce.getContents().toString());
book.setTranscribe(ce.getContents().toString());
book.setPublisher(ce.getContents().toString());
book.setPublishDate(sdf.parse(ce.getContents().toString(), new ParsePosition(0)));
book.setVersion(Integer.parseInt(ce.getContents().toString()));
book.setPage(Integer.parseInt(ce.getContents().toString()));
book.setCls(ce.getContents().toString());
book.setPrecisnotes(ce.getContents().toString());
book.setInstall(ce.getContents().toString());
book.setPrice(Float.parseFloat(ce.getContents().toString()));
book.setUserid(u.getUser().getUserid());
getVector().addElement(book);
}
rwb.close();
fis.close();
} catch (FileNotFoundException e)
{} catch (BiffException e)
{} catch (IOException e)
{} catch (NumberFormatException e)
{
ShowMessage(“數(shù)據(jù)導(dǎo)入失敗,請(qǐng)按照本軟件要求的EXCEL格式導(dǎo)入定單”);
}
關(guān)于java數(shù)據(jù)庫(kù)數(shù)據(jù)導(dǎo)出的介紹到此就結(jié)束了,不知道你從中找到你需要的信息了嗎 ?如果你還想了解更多這方面的信息,記得收藏關(guān)注本站。
成都網(wǎng)站設(shè)計(jì)制作選創(chuàng)新互聯(lián),專業(yè)網(wǎng)站建設(shè)公司。
成都創(chuàng)新互聯(lián)10余年專注成都高端網(wǎng)站建設(shè)定制開發(fā)服務(wù),為客戶提供專業(yè)的成都網(wǎng)站制作,成都網(wǎng)頁(yè)設(shè)計(jì),成都網(wǎng)站設(shè)計(jì)服務(wù);成都創(chuàng)新互聯(lián)服務(wù)內(nèi)容包含成都網(wǎng)站建設(shè),小程序開發(fā),營(yíng)銷網(wǎng)站建設(shè),網(wǎng)站改版,服務(wù)器托管租用等互聯(lián)網(wǎng)服務(wù)。
當(dāng)前名稱:利用Java輕松導(dǎo)出數(shù)據(jù)庫(kù)數(shù)據(jù)——教你如何實(shí)現(xiàn) (java數(shù)據(jù)庫(kù)數(shù)據(jù)導(dǎo)出)
當(dāng)前URL:http://www.dlmjj.cn/article/djdoscd.html


咨詢
建站咨詢
