Ⅰ swing中如何將jtable中的數據導入到excel中
/* * To change this template, choose Tools | Templates * and open the template in the editor. */ package Utils; /////////////////////////////////////////////////// // import import java.awt.event.*; import java.io.*; import javax.swing.*; import javax.swing.table.*; import jxl.*; import jxl.write.*; import jxl.write.biff.RowsExceededException; /** * * @author Administrator */ public class ExcelExporter { public ExcelExporter() { } public void exportTable(JTable table, File file) throws IOException { try { OutputStream out = new FileOutputStream(file); TableModel model = table.getModel(); WritableWorkbook wwb = Workbook.createWorkbook(out); // 創建字表,並寫入數據 WritableSheet ws = wwb.createSheet("中文", 0); // 添加標題 for (int i = 0; i < model.getColumnCount(); i++) { jxl.write.Label labelN = new jxl.write.Label(i, 0, model.getColumnName(i)); try { ws.addCell(labelN); } catch (RowsExceededException e) { // TODO Auto-generated catch block e.printStackTrace(); } catch (WriteException e) { // TODO Auto-generated catch block e.printStackTrace(); } } // 添加列 for (int i = 0; i < model.getColumnCount(); i++) { for (int j = 1; j <= model.getRowCount(); j++) { jxl.write.Label labelN = new jxl.write.Label(i, j, model.getValueAt(j - 1, i).toString()); try { ws.addCell(labelN); } catch (RowsExceededException e) { e.printStackTrace(); } catch (WriteException e) { e.printStackTrace(); } } } wwb.write(); try { wwb.close(); } catch (WriteException e) { e.printStackTrace(); } } catch (FileNotFoundException e) { JOptionPane.showMessageDialog(null, "導入數據前請關閉工作表"); } } public static void main(String[] args) { String[][] data = { {"中文", "$1275.00"}, {"Pets", "$125.00"}, {"Electronics", "$2533.00"}, {"Mensware", "$497.00"} }; String[] headers = {"Department", "Daily Revenue"}; JFrame frame = new JFrame("JTable to Excel Hack"); DefaultTableModel model = new DefaultTableModel(data, headers); final JTable table = new JTable(model); JScrollPane scroll = new JScrollPane(table); JButton export = new JButton("Export"); export.addActionListener(new ActionListener() { public void actionPerformed(ActionEvent evt) { try { ExcelExporter exp = new ExcelExporter(); exp.exportTable(table, new File("results.xls")); } catch (IOException ex) { System.out.println(ex.getMessage()); ex.printStackTrace(); } } }); frame.getContentPane().add("Center", scroll); frame.getContentPane().add("South", export); frame.pack(); frame.setVisible(true); } }
Ⅱ java程序,將Excel表顯示到Swing表格中
table = new JTable(dtModel);
table.setBounds(29, 24, 484, 216);
contentPane.add(table);
String path = textField.getText();
Read read=new Read();
read.openExcel(path);
String[][] data = new String[read.getRowCount(0)][read.getColCount(0)];
for (int i = 0; i <read.getRowCount(0); i++) {
for (int j = 0; j < read.getColCount(0); j++) {
data[i][j] = read.getCellContent(j, i);
}
}
String[] names = new String[] { "1", "2", "3" };
dtModel = new DefaultTableModel(data, names);
textField.getText();是你讀取Excel文件的根目錄版。權
Ⅲ java代碼如何將一個jtable表單中的數據導入到excel表中
將jtable的數據按行讀入到ArrayList裡面然後按照下面的方法處理
try {
Object[] Columns1 = {"會員編號", "姓名", "聯系地址", "電話", "手機", "郵編", "總積分"};
//打開文件
WritableWorkbook book = Workbook.createWorkbook(new File("d:\\CustomerInfo.xls"));
//生成名為「第一頁」的工作表,參數0表示這是第一頁
WritableSheet sheet = book.createSheet("客戶資料", 0);
sheet.addCell(new Label(0, 0, "會員編號"));
sheet.addCell(new Label(1, 0, "姓名"));
sheet.addCell(new Label(2, 0, "聯系地址"));
sheet.addCell(new Label(3, 0, "電話"));
sheet.addCell(new Label(4, 0, "手機"));
sheet.addCell(new Label(5, 0, "郵編"));
sheet.addCell(new Label(6, 0, "會員總積分"));
for (int i = 0; i < list.size(); i++) {
Object[] obj = (Object[]) list.get(i);
for (int j = 0; j < Columns1.length; j++) {
if (j == 0) {
sheet.addCell(new Label(0, i + 1, obj[0].toString()));
} else if (j == 1) {
sheet.addCell(new Label(1, i + 1, obj[1].toString()));
} else if (j == 2) {
sheet.addCell(new Label(2, i + 1, obj[4].toString()));
} else if (j == 3) {
sheet.addCell(new Label(3, i + 1, obj[2].toString()));
} else if (j == 4) {
sheet.addCell(new Label(4, i + 1, obj[3].toString()));
} else if (j == 5) {
sheet.addCell(new Label(5, i + 1, obj[5].toString()));
} else if (j == 6) {
sheet.addCell(new Label(6, i + 1, obj[9].toString()));
}
}
}
/*生成一個保存數字的單元格
必須使用Number的完整包路徑,否則有語法歧義
單元格位置是第二列,第一行,值為789.123*/
// jxl.write.Number numb = new jxl.write.Number(1, 0, 789.123);
// sheet.addCell(numb);
//寫入數據並關閉文件
book.write();
book.close();
GV.MyMSG.myMsg(1, null, "會員資料已導出到文件d:\\CustomerInfo.xls中!~");
// ReleaseManager rm = new ReleaseManager();
// ExcelApplication excel = new ExcelApplication(rm);
// ExcelWorkbooks xlBooks = excel.Workbooks();
// ExcelWorkbook xlBook = xlBooks.Open(outputFile);
// ExcelWorksheet xlSheet = excel.ActiveSheet();
// xlSheet.PrintOut();
// xlBook.Close(false, outputFile, false);
// excel.Quit();
} catch (Exception e) {
System.out.println(e);
}
Ⅳ java如何輸出xls格式的Excel表格文件
有個開源的東東-jxl.jar,可以到http://sourceforge.net/project/showfiles.php?group_id=79926下載。
一.讀取Excel文件內容
/**讀取Excel文件的內容
* @param file 待讀取的文件
* @return
*/
public static String readExcel(File file){
StringBuffer sb = new StringBuffer();
Workbook wb = null;
try {
//構造Workbook(工作薄)對象
wb=Workbook.getWorkbook(file);
} catch (BiffException e) {
e.printStackTrace();
} catch (IOException e) {
e.printStackTrace();
}
if(wb==null)
return null;
//獲得了Workbook對象之後,就可以通過它得到Sheet(工作表)對象了
Sheet[] sheet = wb.getSheets();
if(sheet!=null&&sheet.length>0){
//對每個工作表進行循環
for(int i=0;i<sheet.length;i++){
//得到當前工作表的行數
int rowNum = sheet[i].getRows();
for(int j=0;j<rowNum;j++){
//得到當前行的所有單元格
Cell[] cells = sheet[i].getRow(j);
if(cells!=null&&cells.length>0){
//對每個單元格進行循環
for(int k=0;k<cells.length;k++){
//讀取當前單元格的值
String cellValue = cells[k].getContents();
sb.append(cellValue+" ");
}
}
sb.append(" ");
}
sb.append(" ");
}
}
//最後關閉資源,釋放內存
wb.close();
return sb.toString();
}
二.寫入Excel文件
這里有很多格式了,比如文本內容加粗,加上某些顏色等,可以參考jxl的api,同時還推薦一篇不錯的文章:http://www.ibm.com/developerworks/cn/java/l-javaExcel/?ca=j-t10
/**生成一個Excel文件
* @param fileName 要生成的Excel文件名
*/
public static void writeExcel(String fileName){
WritableWorkbook wwb = null;
try {
//首先要使用Workbook類的工廠方法創建一個可寫入的工作薄(Workbook)對象
wwb = Workbook.createWorkbook(new File(fileName));
} catch (IOException e) {
e.printStackTrace();
}
if(wwb!=null){
//創建一個可寫入的工作表
//Workbook的createSheet方法有兩個參數,第一個是工作表的名稱,第二個是工作表在工作薄中的位置
WritableSheet ws = wwb.createSheet("sheet1", 0);
//下面開始添加單元格
for(int i=0;i<10;i++){
for(int j=0;j<5;j++){
//這里需要注意的是,在Excel中,第一個參數表示列,第二個表示行
Label labelC = new Label(j, i, "這是第"+(i+1)+"行,第"+(j+1)+"列");
try {
//將生成的單元格添加到工作表中
ws.addCell(labelC);
} catch (RowsExceededException e) {
e.printStackTrace();
} catch (WriteException e) {
e.printStackTrace();
}
}
}
try {
//從內存中寫入文件中
wwb.write();
//關閉資源,釋放內存
wwb.close();
} catch (IOException e) {
e.printStackTrace();
} catch (WriteException e) {
e.printStackTrace();
}
}
}
三.在一個Excel文件中查找是否包含某一個關鍵字
/**搜索某一個文件中是否包含某個關鍵字
* @param file 待搜索的文件
* @param keyword 要搜索的關鍵字
* @return
*/
public static boolean searchKeyWord(File file,String keyWord){
boolean res = false;
Workbook wb = null;
try {
//構造Workbook(工作薄)對象
wb=Workbook.getWorkbook(file);
} catch (BiffException e) {
return res;
} catch (IOException e) {
return res;
}
if(wb==null)
return res;
//獲得了Workbook對象之後,就可以通過它得到Sheet(工作表)對象了
Sheet[] sheet = wb.getSheets();
boolean breakSheet = false;
if(sheet!=null&&sheet.length>0){
//對每個工作表進行循環
for(int i=0;i<sheet.length;i++){
if(breakSheet)
break;
//得到當前工作表的行數
int rowNum = sheet[i].getRows();
boolean breakRow = false;
for(int j=0;j<rowNum;j++){
if(breakRow)
break;
//得到當前行的所有單元格
Cell[] cells = sheet[i].getRow(j);
if(cells!=null&&cells.length>0){
boolean breakCell = false;
//對每個單元格進行循環
for(int k=0;k<cells.length;k++){
if(breakCell)
break;
//讀取當前單元格的值
String cellValue = cells[k].getContents();
if(cellValue==null)
continue;
if(cellValue.contains(keyWord)){
res = true;
breakCell = true;
breakRow = true;
breakSheet = true;
}
}
}
}
}
}
//最後關閉資源,釋放內存
wb.close();
return res;
}
四.往Excel中插入圖片圖標
插入圖片的實現很容易,參看以下代碼:
/**往Excel中插入圖片
* @param dataSheet 待插入的工作表
* @param col 圖片從該列開始
* @param row 圖片從該行開始
* @param width 圖片所佔的列數
* @param height 圖片所佔的行數
* @param imgFile 要插入的圖片文件
*/
public static void insertImg(WritableSheet dataSheet, int col, int row, int width,
int height, File imgFile){
WritableImage img = new WritableImage(col, row, width, height, imgFile);
dataSheet.addImage(img);
}
以上代碼的注釋已經很清楚了,大概也就不用再解釋了,我們可以用如下程序驗證:
try {
//創建一個工作薄
WritableWorkbook workbook = Workbook.createWorkbook(new File("D:/test1.xls"));
//待插入的工作表
WritableSheet imgSheet = workbook.createSheet("Images",0);
//要插入的圖片文件
File imgFile = new File("D:/1.png");
//圖片插入到第二行第一個單元格,長寬各佔六個單元格
insertImg(imgSheet,0,1,6,6,imgFile);
workbook.write();
workbook.close();
} catch (IOException e) {
e.printStackTrace();
} catch (WriteException e) {
e.printStackTrace();
}
但是jxl只支持png格式的圖片,jpg格式和gif格式都不支持
五.插入頁眉頁腳
一般的頁眉頁腳都分為三個部分,左,中,右三部分,利用如下代碼可實現插入頁眉頁腳
/**向Excel中加入頁眉頁腳
* @param dataSheet 待加入頁眉的工作表
* @param left
* @param center
* @param right
*/
public static void setHeader(WritableSheet dataSheet,String left,String center,String right){
HeaderFooter hf = new HeaderFooter();
hf.getLeft().append(left);
hf.getCentre().append(center);
hf.getRight().append(right);
//加入頁眉
dataSheet.getSettings().setHeader(hf);
//加入頁腳
//dataSheet.getSettings().setFooter(hf);
}
我們可以用如下代碼測試該方法:
try {
//創建一個工作薄
WritableWorkbook workbook = Workbook.createWorkbook(new File("D:/test1.xls"));
//待插入的工作表
WritableSheet dataSheet = workbook.createSheet("加入頁眉",0);
ExcelUtils.setHeader(dataSheet, "chb", "2007-03-06", "第1頁,共3頁");
workbook.write();
workbook.close();
} catch (IOException e) {
e.printStackTrace();
} catch (WriteException e) {
e.printStackTrace();
}
六偷懶工具設計之sql2Excel
今天在公司陪山東客戶調試,遠程登錄,我在linux下什麼工具都沒有,用ssh登錄伺服器,直接用mysql查詢資料庫,提出記錄中的所有漢字全是亂碼。哎,可惡的公司,不讓我用windows,要不我就可以用putty或者EMS了,我ft!
甚是不爽之下,我決定自己寫個工具了,把客戶資料庫中的數據全部提取並保存到Excel中,這樣我不就可以一目瞭然了嘛,嘿嘿,好吧,那我就寫一個工具吧。
第一部分就是誰都會的jdbc操作,連接資料庫,提取數據集合。
Connection con;
Statement state;
/**初始化連接
* @param serverIp
* @param dataBase
* @param userName
* @param password
* @throws ClassNotFoundException
* @throws SQLException
*/
public void init(String serverIp,String dataBase,String userName,String password) throws ClassNotFoundException, SQLException{
Class.forName("com.mysql.jdbc.Driver");
//配置數據源
String url="jdbc:mysql://"+serverIp+"/"+dataBase+"?useUnicode=true&characterEncoding=GB2312";
con=DriverManager.getConnection(url,userName,password);
}
/**得到查詢結果集
* @param sql
* @return
* @throws SQLException
*/
public ResultSet getResultSet(String sql) throws SQLException{
state = con.createStatement();
ResultSet res = state.executeQuery(sql);
return res;
}
/**關閉連接
* @throws SQLException
*/
public void close() throws SQLException{
if(con!=null)
con.close();
if(state!=null)
state.close();
}
第二部分就是把ResultSet中的記錄寫入一個Excel文件
操作Excel,我用的是jxl,不熟的同學可以參考:利用java操作Excel文件
/**將查詢結果寫入Excel文件中
* @param rs
* @param file
* @throws SQLException
*/
public void writeExcel(ResultSet rs,File file) throws SQLException{
WritableWorkbook wwb = null;
try{
//首先要使用Workbook類的工廠方法創建一個可寫入的工作薄(Workbook)對象
wwb = Workbook.createWorkbook(file);
} catch (IOException e){
e.printStackTrace();
}
if(wwb!=null){
WritableSheet ws = wwb.createSheet("sheet1", 0);
int i=0;
while(rs.next()){
Label label1 = new Label(0, i, rs.getString("id"));
Label label2 = new Label(1, i, rs.getString("category"));
try {
ws.addCell(label1);
ws.addCell(label2);
} catch (RowsExceededException e) {
e.printStackTrace();
} catch (WriteException e) {
e.printStackTrace();
}
i++;
}
try {
//從內存中寫入文件中
wwb.write();
//關閉資源,釋放內存
wwb.close();
} catch (IOException e) {
e.printStackTrace();
} catch (WriteException e){
e.printStackTrace();
}
}
}
測試程序:
Sql2Excel se = new Sql2Excel();
try {
se.init("127.0.0.1","mydabase", "root", "1234");
ResultSet rs = se.getResultSet("select id,category from xx ");
se.writeExcel(rs, new File("/root/sql2excel.xls"));
se.close();
} catch (ClassNotFoundException e) {
e.printStackTrace();
} catch (SQLException e) {
e.printStackTrace();
}
Ⅳ java JTable控制項按表頭排序後,將排序後的數據導出Excel,但Excel數據內容還是排序之前的數據,怎麼解決
用jxl.jar把很方便好用
http://hi..com/zbzb/blog/item/95c4ac1804a8600734fa4100.html
這是包下載地址。
這是例子:
import jxl.*;
import jxl.write.*;
import java.io.*;
import java.io.File.*;
import java.util.*;
public class excel
{
public static void main(String[] args)
{
String targetfile = "c:/out.xls";//輸出的excel文件名
String worksheet = "List";//輸出的excel文件工作表名
String[] title = {"ID","NAME","DESCRIB"};//excel工作表的標題
WritableWorkbook workbook;
try
{
//創建可寫入的Excel工作薄,運行生成的文件在tomcat/bin下
//workbook = Workbook.createWorkbook(new File("output.xls"));
System.out.println("begin");
OutputStream os=new FileOutputStream(targetfile);
workbook=Workbook.createWorkbook(os);
WritableSheet sheet = workbook.createSheet(worksheet, 0); //添加第一個工作表
//WritableSheet sheet1 = workbook.createSheet("MySheet1", 1); //可添加第二個工作
/*
jxl.write.Label label = new jxl.write.Label(0, 2, "A label record"); //put a label in cell A3, Label(column,row)
sheet.addCell(label);
*/
jxl.write.Label label;
for (int i=0; i<title.length; i++)
{
//Label(列號,行號 ,內容 )
label = new jxl.write.Label(i, 0, title[i]); //put the title in row1
sheet.addCell(label);
}
//下列添加的對字體等的設置均調試通過,可作參考用
//添加數字
jxl.write.Number number = new jxl.write.Number(3, 4, 3.14159); //put the number 3.14159 in cell D5
sheet.addCell(number);
//添加帶有字型Formatting的對象
jxl.write.WritableFont wf = new jxl.write.WritableFont(WritableFont.TIMES,10,WritableFont.BOLD,true);
jxl.write.WritableCellFormat wcfF = new jxl.write.WritableCellFormat(wf);
jxl.write.Label labelCF = new jxl.write.Label(4,4,"文本",wcfF);
sheet.addCell(labelCF);
//添加帶有字體顏色,帶背景顏色 Formatting的對象
jxl.write.WritableFont wfc = new jxl.write.WritableFont(WritableFont.ARIAL,10,WritableFont.BOLD,false,jxl.format.UnderlineStyle.NO_UNDERLINE,jxl.format.Colour.RED);
jxl.write.WritableCellFormat wcfFC = new jxl.write.WritableCellFormat(wfc);
wcfFC.setBackground(jxl.format.Colour.BLUE);
jxl.write.Label labelCFC = new jxl.write.Label(1,5,"帶顏色",wcfFC);
sheet.addCell(labelCFC);
//添加帶有formatting的Number對象
jxl.write.NumberFormat nf = new jxl.write.NumberFormat("#.##");
jxl.write.WritableCellFormat wcfN = new jxl.write.WritableCellFormat(nf);
jxl.write.Number labelNF = new jxl.write.Number(1,1,3.1415926,wcfN);
sheet.addCell(labelNF);
//3.添加Boolean對象
jxl.write.Boolean labelB = new jxl.write.Boolean(0,2,false);
sheet.addCell(labelB);
//4.添加DateTime對象
jxl.write.DateTime labelDT = new jxl.write.DateTime(0,3,new java.util.Date());
sheet.addCell(labelDT);
//添加帶有formatting的DateFormat對象
jxl.write.DateFormat df = new jxl.write.DateFormat("ddMMyyyyhh:mm:ss");
jxl.write.WritableCellFormat wcfDF = new jxl.write.WritableCellFormat(df);
jxl.write.DateTime labelDTF = new jxl.write.DateTime(1,3,new java.util.Date(),wcfDF);
sheet.addCell(labelDTF);
//和賓單元格
//sheet.mergeCells(int col1,int row1,int col2,int row2);//左上角到右下角
sheet.mergeCells(4,5,8,10);//左上角到右下角
wfc = new jxl.write.WritableFont(WritableFont.ARIAL,40,WritableFont.BOLD,false,jxl.format.UnderlineStyle.NO_UNDERLINE,jxl.format.Colour.GREEN);
jxl.write.WritableCellFormat wchB = new jxl.write.WritableCellFormat(wfc);
wchB.setAlignment(jxl.format.Alignment.CENTRE);
labelCFC = new jxl.write.Label(4,5,"單元合並",wchB);
sheet.addCell(labelCFC); //
//設置邊框
jxl.write.WritableCellFormat wcsB = new jxl.write.WritableCellFormat();
wcsB.setBorder(jxl.format.Border.ALL,jxl.format.BorderLineStyle.THICK);
labelCFC = new jxl.write.Label(0,6,"邊框設置",wcsB);
sheet.addCell(labelCFC);
workbook.write();
workbook.close();
}catch(Exception e)
{
e.printStackTrace();
}
System.out.println("end");
Runtime r=Runtime.getRuntime();
Process p=null;
//String cmd[]={"notepad","exec.java"};
String cmd[]={"C:\\Program Files\\Microsoft Office\\Office\\EXCEL.EXE","out.xls"};
try{
p=r.exec(cmd);
}
catch(Exception e){
System.out.println("error executing: "+cmd[0]);
}
}
}