Export File for SQLServe

import java.awt.Color;
import java.awt.Component;
import java.awt.EventQueue;
import java.awt.Label;
import java.awt.Toolkit;
import java.awt.datatransfer.Clipboard;
import java.awt.datatransfer.DataFlavor;
import java.awt.datatransfer.StringSelection;
import java.awt.event.ActionEvent;
import java.awt.event.ActionListener;
import java.awt.event.FocusEvent;
import java.awt.event.FocusListener;
import java.awt.event.ItemEvent;
import java.awt.event.ItemListener;
import java.awt.event.MouseEvent;
import java.io.BufferedWriter;
import java.io.File;
import java.io.FileOutputStream;
import java.io.FileWriter;
import java.io.IOException;
import java.io.PrintWriter;
import java.sql.ResultSet;
import java.sql.ResultSetMetaData;
import java.sql.SQLException;
import java.util.Arrays;

import javax.swing.JButton;
import javax.swing.JComboBox;
import javax.swing.JFileChooser;
import javax.swing.JFrame;
import javax.swing.JOptionPane;
import javax.swing.JPanel;
import javax.swing.JScrollPane;
import javax.swing.JTable;
import javax.swing.JTextArea;
import javax.swing.JTextField;
import javax.swing.ListSelectionModel;
import javax.swing.ScrollPaneConstants;
import javax.swing.border.EmptyBorder;
import javax.swing.table.DefaultTableModel;
import javax.swing.table.TableCellRenderer;
import javax.swing.table.TableColumn;

import org.apache.poi.ss.usermodel.BorderStyle;
import org.apache.poi.ss.usermodel.FillPatternType;
import org.apache.poi.ss.usermodel.HorizontalAlignment;
import org.apache.poi.ss.usermodel.IndexedColors;
import org.apache.poi.xssf.usermodel.XSSFCell;
import org.apache.poi.xssf.usermodel.XSSFCellStyle;
import org.apache.poi.xssf.usermodel.XSSFFont;
import org.apache.poi.xssf.usermodel.XSSFRow;
import org.apache.poi.xssf.usermodel.XSSFSheet;
import org.apache.poi.xssf.usermodel.XSSFWorkbook;

public class SelSql extends JFrame {

private JPanel contentPane;
private JTextField textField;
private JTextArea textArea;

private JTable table;
private JComboBox<String> comboBox;
private String coltype[];
private int order;

private static final String LINE_BREAK = "\n";
private static final String CELL_BREAK = "\t";
private static final Clipboard CLIPBOARD = Toolkit.getDefaultToolkit().getSystemClipboard();

/**
* Launch the application.
*/
public static void main(String[] args) {
EventQueue.invokeLater(new Runnable() {
public void run() {
try {
SelSql frame = new SelSql();
frame.setVisible(true);
} catch (Exception e) {
e.printStackTrace();
}
}
});
}

/**
* Create the frame.
*/
@SuppressWarnings("static-access")
public SelSql() {
setTitle("SelSql");

setDefaultCloseOperation(JFrame.EXIT_ON_CLOSE);
setBounds(100, 100, 704, 672);
contentPane = new JPanel();
contentPane.setBorder(new EmptyBorder(5, 5, 5, 5));
setContentPane(contentPane);
contentPane.setLayout(null);

Label label = new Label("SqlServerテーブル選択Free");
label.setBounds(23, 10, 246, 23);
label.setBackground(new Color(255, 182, 193));
contentPane.add(label);

Label label_1 = new Label("テーブル名");
label_1.setAlignment(Label.CENTER);
label_1.setBounds(23, 59, 89, 23);
label_1.setBackground(new Color(72, 209, 204));
contentPane.add(label_1);

JTextArea textArea = new JTextArea("", 5, 20);
textArea.addFocusListener(new FocusListener() {

@Override
public void focusGained(FocusEvent e) {
// TODO 自動生成されたメソッド・スタブ
order=1;
}

@Override
public void focusLost(FocusEvent e) {
// TODO 自動生成されたメソッド・スタブ
order=1;
}

});
JScrollPane scrollpane2 = new JScrollPane(textArea,
JScrollPane.VERTICAL_SCROLLBAR_ALWAYS,
JScrollPane.HORIZONTAL_SCROLLBAR_ALWAYS);
scrollpane2.setSize(565, 215);
scrollpane2.setLocation(115, 90);
contentPane.add(scrollpane2);

textField = new JTextField();
textField.setBounds(114, 59, 155, 23);
contentPane.add(textField);
textField.addFocusListener(new FocusListener() {
@Override
public void focusGained(FocusEvent e) {
// TODO 自動生成されたメソッド・スタブ
order=5;
}

@Override
public void focusLost(FocusEvent e) {
// TODO 自動生成されたメソッド・スタブ
order=5;
}

});
textField.setColumns(100);

JScrollPane scrollPane = new JScrollPane();
scrollPane.setVerticalScrollBarPolicy(ScrollPaneConstants.VERTICAL_SCROLLBAR_ALWAYS);
scrollPane.setHorizontalScrollBarPolicy(ScrollPaneConstants.HORIZONTAL_SCROLLBAR_ALWAYS);
scrollPane.setBounds(23, 317, 659, 293);
getContentPane().add(scrollPane);

String[] columnNames = {};
DefaultTableModel tableModel
= new DefaultTableModel(columnNames, 0);
JTable table = new JTable(tableModel){
@Override
public Component prepareRenderer(TableCellRenderer renderer, int row, int column) {
Component component = super.prepareRenderer(renderer, row, column);
int rendererWidth = component.getPreferredSize().width;
TableColumn tableColumn = getColumnModel().getColumn(column);
tableColumn.setPreferredWidth(Math.max(rendererWidth + getIntercellSpacing().width, tableColumn.getPreferredWidth()));
return component;
}
};
table.setCellSelectionEnabled(true);
table.setAutoResizeMode(JTable.AUTO_RESIZE_OFF);//セルの自動サイズ設定をoffにしています。
table.setSelectionMode(ListSelectionModel.SINGLE_INTERVAL_SELECTION);
//編集不可
table.setDefaultEditor(Object.class, null);
//テーブルにマウスイベントを付ける
table.addMouseListener(new java.awt.event.MouseAdapter() {
public void mouseClicked(MouseEvent e) {
// 選択行の行番号を取得します
int row = table.getSelectedRow();
//int col = table.getSelectedColumn();

//System.out.println("行" + row + "::" + "列" + col);
//System.out.println(tableModel.getValueAt(row, 0).toString());
//textField_1.setText(tableModel.getValueAt(row, 0).toString());
}
});
table.addFocusListener(new FocusListener() {

@Override
public void focusGained(FocusEvent e) {
// TODO 自動生成されたメソッド・スタブ
order=6;
}

@Override
public void focusLost(FocusEvent e) {
// TODO 自動生成されたメソッド・スタブ
order=6;
}

});
scrollPane.setViewportView(table);

JButton btnNewButton = new JButton("選 択");
btnNewButton.setBounds(287, 10, 91, 21);
btnNewButton.addActionListener(new ActionListener() {

//static access
@SuppressWarnings("static-access")
public void actionPerformed(ActionEvent e) {

//検索;
Connect Con = new Connect();
Con.open();

ResultSet rs = null;
String Str = "";
//テーブル指定

//選択項目?
if (textArea.getText().equals("")) {
if (textField.getText().equals("")) {
JOptionPane.showMessageDialog(btnNewButton,"テーブルがありません。",
"インフォメーション", JOptionPane.INFORMATION_MESSAGE);
return;
} else {
Str = "SELECT * FROM " + textField.getText() ;
}
} else {
Str = textArea.getText() ;
}

//列を0にします。
tableModel.setColumnCount(0);
//行を0にします。
tableModel.setRowCount(0);

//行を削除します。
//int rowcount= tableModel.getRowCount();
//for(int i = 0 ; i < rowcount ; i++){
// //tableModel.removeRow(rowcount - i - 1);
//}

try {

//データ取得
rs = Con.stmt.executeQuery(Str);

//メタデータ取得
ResultSetMetaData rsmd = rs.getMetaData();

//列数の獲得
int columnsNumber = rsmd.getColumnCount();
coltype = new String[columnsNumber];
Arrays.fill(coltype, "");

//System.out.println("columns: "+rsmd.getColumnCount());
//System.out.println("Column Name of 1st column: "+rsmd.getColumnName(1));
//System.out.println("Column Type Name of 1st column: "+rsmd.getColumnTypeName(1));
//System.out.println("Column Display Size of 1st column: "+rsmd.getColumnDisplaySize(1));
//System.out.println("Column Scale of 1st column: "+rsmd.getScale(1));

//列名を追加
for (int i=0 ; i<rsmd.getColumnCount(); i++) {
tableModel.addColumn(rsmd.getColumnName(i+1));
coltype[i]=rsmd.getColumnTypeName(i+1);
//System.out.println(coltype[i]);
}
//DefaultTableColumnModel columnModel
//= (DefaultTableColumnModel)table.getColumnModel();
//TableColumn column = null;
//列名を追加
//for (int i=0 ; i<rsmd.getColumnCount(); i++) {
// column = columnModel.getColumn(i+1);
// column.setPreferredWidth(rsmd.getColumnDisplaySize(i+1));
//}

//行データ用
Object[]row = new Object[columnsNumber];

//列名を追加
for (int i=0 ; i<rsmd.getColumnCount(); i++) {
row[i]=rsmd.getColumnName(i+1);
//System.out.println(coltype[i]);
}
//行を追加
tableModel.addRow(row);

while (rs.next()) {

//列データセット
for (int i=0 ; i<columnsNumber ; i++) {
row[i]=rs.getString(i+1);
}

//行を追加
tableModel.addRow(row);
//System.out.println(row[0] + " " + row[1]);
}

rs.close();

}catch(SQLException ex) {

System.out.println("検索に失敗しました。");
JOptionPane.showMessageDialog(btnNewButton,"テーブルがありません。",
"インフォメーション", JOptionPane.INFORMATION_MESSAGE);
if(rs!=null)
try{rs.close();}catch(Exception e2){ex.printStackTrace();}
ex.printStackTrace();

}

Con.close();
}
});
contentPane.add(btnNewButton);

JButton btnNewButton_1 = new JButton("CSV");
btnNewButton_1.setBounds(390, 10, 91, 21);
btnNewButton_1.addActionListener(new ActionListener() {
public void actionPerformed(ActionEvent e) {

JFileChooser filechooser = new JFileChooser();
filechooser.setSelectedFile(new File("c:\\sample", textField.getText()+".csv"));
String CsvPath="";

int selected = filechooser.showSaveDialog(btnNewButton_1);

if (selected == JFileChooser.APPROVE_OPTION){
File file = filechooser.getSelectedFile();
CsvPath=file.getAbsolutePath();

}else if (selected == JFileChooser.CANCEL_OPTION){
JOptionPane.showMessageDialog(btnNewButton,"キャンセルされました",
"インフォメーション", JOptionPane.INFORMATION_MESSAGE);
return;

}else if (selected == JFileChooser.ERROR_OPTION){
JOptionPane.showMessageDialog(btnNewButton,"エラー又は取消しがありました",
"インフォメーション", JOptionPane.INFORMATION_MESSAGE);
return;
}

// 出力ファイルの作成
FileWriter f = null;
try {
f = new FileWriter(CsvPath, false);
} catch (IOException e1) {
// TODO 自動生成された catch ブロック
e1.printStackTrace();
JOptionPane.showMessageDialog(btnNewButton,"ファイル作成できません。",
"インフォメーション", JOptionPane.INFORMATION_MESSAGE);
return;
}

PrintWriter p = new PrintWriter(new BufferedWriter(f));

int cols = table.getColumnCount();
int rows = table.getRowCount();

//列名
for (int j=0; j<table.getColumnCount(); j++) {
Object val = table.getColumnName(j);
if (val != null) {
p.print("\"" + val + "\"");
}
if (j < cols-1) {
p.print(',');
}
}
p.println();

//行値
for (int i=1; i<rows; i++) {
for (int j=0; j<cols; j++) {
Object val = table.getValueAt(i, j);
if (val != null) {
p.print("\"" + val + "\"");
}
if (j < cols-1) {
p.print(',');
}
}
p.println();
}

//クローズ
p.close();

JOptionPane.showMessageDialog(btnNewButton,"CSVを作成しました。",
"インフォメーション", JOptionPane.INFORMATION_MESSAGE);
}
});
contentPane.add(btnNewButton_1);

JButton btnNewButton_2 = new JButton("終 了");
btnNewButton_2.setBounds(591, 10, 91, 21);
btnNewButton_2.addActionListener(new ActionListener() {
public void actionPerformed(ActionEvent e) {

//System.exit(0);
dispose();
}
});
contentPane.add(btnNewButton_2);

Label label_4 = new Label("SQL文");
label_4.setAlignment(Label.CENTER);
label_4.setBackground(new Color(72, 209, 204));
label_4.setBounds(23, 88, 89, 219);
contentPane.add(label_4);

JComboBox<String> comboBox = new JComboBox();
comboBox.setBounds(270, 59, 412, 23);
comboBox.addItemListener(new ItemListener() {
public void itemStateChanged(ItemEvent e) {
if (e.getStateChange() == ItemEvent.SELECTED){
textField.setText((String) comboBox.getSelectedItem());

}
}
});
contentPane.add(comboBox);

JButton btnExcel = new JButton("Excel");
btnExcel.setBounds(488, 10, 91, 21);
btnExcel.addActionListener(new ActionListener() {
public void actionPerformed(ActionEvent e) {

JFileChooser filechooser = new JFileChooser();
filechooser.setSelectedFile(new File("c:\\sample", textField.getText()+".xlsx"));
String ExcelPath="";

int selected = filechooser.showSaveDialog(btnNewButton_1);

if (selected == JFileChooser.APPROVE_OPTION){
File file = filechooser.getSelectedFile();
ExcelPath=file.getAbsolutePath();

}else if (selected == JFileChooser.CANCEL_OPTION){
JOptionPane.showMessageDialog(btnNewButton,"キャンセルされました",
"インフォメーション", JOptionPane.INFORMATION_MESSAGE);
return;

}else if (selected == JFileChooser.ERROR_OPTION){
JOptionPane.showMessageDialog(btnNewButton,"エラー又は取消しがありました",
"インフォメーション", JOptionPane.INFORMATION_MESSAGE);
return;
}

int cols = table.getColumnCount();
int rows = table.getRowCount();
//System.out.println(cols + " " + rows);

// ワークブック
XSSFWorkbook workBook = null;
// シート
XSSFSheet sheet = null;
// 出力ファイル
FileOutputStream outPutFile = null;
// 出力ファイルパス
//String outPutFilePath = null;
// 出力ファイル名
//String outPutFileName = null;

// エクセルファイルの作成
try {

// ワークブックの作成
workBook = new XSSFWorkbook();

// シートの設定
sheet = workBook.createSheet();
workBook.setSheetName(0, textField.getText());
sheet = workBook.getSheet(textField.getText());

// 初期行の作成
XSSFRow row = sheet.createRow(1);

// 「タイトル」のセルスタイル設定
XSSFCellStyle titleCellStyle = workBook.createCellStyle();
XSSFCell cell = row.createCell(1);
XSSFFont titleFont = workBook.createFont();
titleFont.setFontName("MS 明朝");
titleFont.setFontHeightInPoints((short)14);
titleFont.setUnderline(XSSFFont.U_SINGLE);
titleCellStyle.setFont(titleFont);
cell.setCellStyle(titleCellStyle);

// セルに「タイトル」を設定
cell.setCellValue(textField.getText());

// 「表のヘッダ」のセルスタイル設定
XSSFCellStyle headerCellStyle = workBook.createCellStyle();
XSSFFont headerFont = workBook.createFont();
headerFont.setFontName("MS 明朝");
headerFont.setFontHeightInPoints((short)12);
headerCellStyle.setFont(headerFont);
headerCellStyle.setFillPattern(FillPatternType.SOLID_FOREGROUND);
headerCellStyle.setAlignment(HorizontalAlignment.CENTER);
headerCellStyle.setFillForegroundColor(IndexedColors.AQUA.index);
headerCellStyle.setBorderTop(BorderStyle.THIN);
headerCellStyle.setBorderBottom(BorderStyle.THIN);
headerCellStyle.setBorderRight(BorderStyle.THIN);
headerCellStyle.setBorderLeft(BorderStyle.THIN);

// セルに「表のヘッダ」を設定
row = sheet.createRow(4);

//列名
for (int j=0; j<table.getColumnCount(); j++) {
cell = row.createCell(j);
cell.setCellStyle(headerCellStyle);
String val = table.getColumnName(j);
if (val != null) {
cell.setCellValue(val);
} else {
cell.setCellValue("");
}
}

// 「行」のセルスタイル設定
XSSFCellStyle resultCellStyle = workBook.createCellStyle();
XSSFFont resultFont = workBook.createFont();
resultFont.setFontName("MS 明朝");
resultFont.setFontHeightInPoints((short)11);
resultCellStyle.setFont(resultFont);
//resultCellStyle.setFillPattern(FillPatternType.SOLID_FOREGROUND);
//resultCellStyle.setAlignment(HorizontalAlignment.JUSTIFY);
//resultCellStyle.setFillForegroundColor(IndexedColors.WHITE.index);
resultCellStyle.setBorderTop(BorderStyle.THIN);
resultCellStyle.setBorderBottom(BorderStyle.THIN);
resultCellStyle.setBorderRight(BorderStyle.THIN);
resultCellStyle.setBorderLeft(BorderStyle.THIN);

//行値(一行目の見出しを除外)
for (int i=1; i<rows; i++) {
row = sheet.createRow(i+4);
for (int j=0; j<cols; j++) {
cell = row.createCell(j);
cell.setCellStyle(resultCellStyle);
String val = (String) table.getValueAt(i, j);

if (val != null) {
cell.setCellValue(val);
if (coltype[j].equals("numeric")==true) {
cell.setCellValue(Integer.parseInt(val));
}else if (coltype[j].equals("decimal")==true) {
cell.setCellValue(Double.parseDouble(val));
}else if (coltype[j].equals("int")==true) {
cell.setCellValue(Integer.parseInt(val));
}else if (coltype[j].equals("bigint")==true) {
cell.setCellValue(Long.parseLong(val));
}else if (coltype[j].equals("smallint")==true) {
cell.setCellValue(Integer.parseInt(val));
}
}else {
cell.setCellValue("");
}
}
}

// エクセルファイルを出力
try {

// 現在の日付を取得
//Date date = new Date();
//SimpleDateFormat dateFormat = new SimpleDateFormat("yyyyMMdd");

//ファイルパス・ファイル名の指定
//outPutFilePath = "出力したいファイルパス";
//outPutFileName = "kuku_" + dateFormat.format(date).toString() + ".xlsx";

// エクセルファイルを出力
outPutFile = new FileOutputStream(ExcelPath);
workBook.write(outPutFile);

//クローズ
workBook.close();

//System.out.println("「" + ExcelPath + "」を出力しました。");
JOptionPane.showMessageDialog(btnNewButton,"Excelを作成しました。",
"インフォメーション", JOptionPane.INFORMATION_MESSAGE);

}catch(IOException e3) {
System.out.println(e3.toString());
}

}catch(Exception e2) {
System.out.println(e2.toString());
}

}
});
contentPane.add(btnExcel);

JButton btn_cut = new JButton("cut");
btn_cut.setBounds(390, 28, 91, 21);
btn_cut.addActionListener(new ActionListener() {
public void actionPerformed(ActionEvent e) {
if (order==1) {
textArea.cut();
} else if (order==5) {
textField.cut();
} else if (order==6) {

int numCols=table.getSelectedColumnCount();
int numRows=table.getSelectedRowCount();
int[] rowsSelected=table.getSelectedRows();
int[] colsSelected=table.getSelectedColumns();
if (numRows!=rowsSelected[rowsSelected.length-1]-rowsSelected[0]+1 || numRows!=rowsSelected.length ||
numCols!=colsSelected[colsSelected.length-1]-colsSelected[0]+1 || numCols!=colsSelected.length) {

JOptionPane.showMessageDialog(null, "Invalid Copy Selection", "Invalid Copy Selection", JOptionPane.ERROR_MESSAGE);
return;
}

StringBuffer excelStr=new StringBuffer();
for (int i=0; i<numRows; i++) {
for (int j=0; j<numCols; j++) {
excelStr.append(escape(table.getValueAt(rowsSelected[i], colsSelected[j])));
//if (isCut) {
table.setValueAt(null, rowsSelected[i], colsSelected[j]);
//}
if (j<numCols-1) {
excelStr.append(CELL_BREAK);
}
}
excelStr.append(LINE_BREAK);
}

StringSelection sel = new StringSelection(excelStr.toString());
CLIPBOARD.setContents(sel, sel);
}
}
private String escape(Object cell) {
return cell.toString().replace(LINE_BREAK, " ").replace(CELL_BREAK, " ");
}
});
contentPane.add(btn_cut);

JButton btn_copy = new JButton("copy");
btn_copy.setBounds(488, 28, 91, 21);
btn_copy.addActionListener(new ActionListener() {
public void actionPerformed(ActionEvent e) {
if (order==1) {
textArea.copy();
} else if (order==5) {
textField.copy();
} else if (order==6) {

int numCols=table.getSelectedColumnCount();
int numRows=table.getSelectedRowCount();
int[] rowsSelected=table.getSelectedRows();
int[] colsSelected=table.getSelectedColumns();
if (numRows!=rowsSelected[rowsSelected.length-1]-rowsSelected[0]+1 || numRows!=rowsSelected.length ||
numCols!=colsSelected[colsSelected.length-1]-colsSelected[0]+1 || numCols!=colsSelected.length) {

JOptionPane.showMessageDialog(null, "Invalid Copy Selection", "Invalid Copy Selection", JOptionPane.ERROR_MESSAGE);
return;
}

StringBuffer excelStr=new StringBuffer();
for (int i=0; i<numRows; i++) {
for (int j=0; j<numCols; j++) {
excelStr.append(escape(table.getValueAt(rowsSelected[i], colsSelected[j])));
//if (isCut) {
// table.setValueAt(null, rowsSelected[i], colsSelected[j]);
//}
if (j<numCols-1) {
excelStr.append(CELL_BREAK);
}
}
excelStr.append(LINE_BREAK);
}

StringSelection sel = new StringSelection(excelStr.toString());
CLIPBOARD.setContents(sel, sel);
}
}
private String escape(Object cell) {
return cell.toString().replace(LINE_BREAK, " ").replace(CELL_BREAK, " ");
}
});
contentPane.add(btn_copy);

JButton btn_paste = new JButton("paste");
btn_paste.setBounds(591, 28, 91, 21);
btn_paste.addActionListener(new ActionListener() {
public void actionPerformed(ActionEvent e) {
if (order==1) {
textArea.paste();
} else if (order==5) {
textField.paste();
} else if (order==6) {

int startRow=table.getSelectedRows()[0];
int startCol=table.getSelectedColumns()[0];

String pasteString = "";
try {
pasteString = (String)(CLIPBOARD.getContents(this).getTransferData(DataFlavor.stringFlavor));
} catch (Exception e2) {
JOptionPane.showMessageDialog(null, "Invalid Paste Type", "Invalid Paste Type", JOptionPane.ERROR_MESSAGE);
return;
}

String[] lines = pasteString.split(LINE_BREAK);
for (int i=0 ; i<lines.length; i++) {
String[] cells = lines[i].split(CELL_BREAK);
for (int j=0 ; j<cells.length; j++) {
if (table.getRowCount()>startRow+i && table.getColumnCount()>startCol+j) {
table.setValueAt(cells[j], startRow+i, startCol+j);
}
}
}

}
}

});
contentPane.add(btn_paste);

//空行追加
comboBox.addItem("");

//comboBoxへテーブル名を追加
Connect Con = new Connect();
Con.open();
// *********************************************************
// データベースのメタデータを取得
// *********************************************************
Con.getMetaData();
// *********************************************************
// テーブル一覧を返すリザルトセットを取得
// *********************************************************
try {
ResultSet rs = null;

String types[] = { "TABLE" };
rs =Con.objMet.getTables(null, null,"%", types);

while( rs.next() ) {
//System.out.println(rs.getString("TABLE_NAME"));
comboBox.addItem((rs.getString("TABLE_NAME")).toString());
}
rs.close();

} catch (SQLException e1) {
// TODO 自動生成された catch ブロック
e1.printStackTrace();
}

//Con.close();
}
}

PAGE TOP