Java : Apache POI で最低限の処理を標準化( ここではワークブックは新規作成 )

最新の Excel( .xslx ) 用 XSSF に必要な jar

Apache POI Apache Commons Collections Apache Commons Compress 4.1 ドキュメント

サンプル

オーバーロードを使用して、できるだけ cell というメソッドでできるようにしてみました。Microsoft の仕様に合わせて行や列を 1 始まりにしたかったという意図もあります。
import java.io.FileOutputStream;
import java.text.SimpleDateFormat;
import java.util.Date;

import org.apache.poi.ss.usermodel.BorderStyle;
import org.apache.poi.ss.usermodel.CellType;
import org.apache.poi.ss.util.CellRangeAddress;
import org.apache.poi.ss.util.RegionUtil;
import org.apache.poi.xssf.usermodel.XSSFCell;
import org.apache.poi.xssf.usermodel.XSSFCellStyle;
import org.apache.poi.xssf.usermodel.XSSFRow;
import org.apache.poi.xssf.usermodel.XSSFSheet;
import org.apache.poi.xssf.usermodel.XSSFWorkbook;
import org.apache.poi.xssf.usermodel.XSSFWorkbookFactory;

public class Main {

    private static XSSFWorkbook book;
    private static XSSFSheet  sheet;

    // *****************************************************
    // エントリポイント
    // *****************************************************
    public static void main(String[] args) {
        try {
            // ****************************
            // ブック作成
            // ****************************
            book = XSSFWorkbookFactory.createWorkbook();

            // ****************************
            // シート作成
            // ****************************
            sheet = book.createSheet("Javaの処理");

            // ****************************
            // セルに値を直接セット
            // ****************************
            for (int i = 1; i <= 10; i++)
            {
                cell( sheet, i, 1, String.format("処理 : %d", i ));
            }

            // ****************************
            // セルの幅( 3列目 )
            // ****************************
            cellWidth( sheet, 3, 6000 );

            // ****************************
            // セルの結合
            // ****************************
            cell( sheet, 1, 3, 1, 5 );
            // 結合されたセルに値をセット
            cell( sheet, 1, 3, "結合されたセル" );
            
            // ****************************
            // 日付のセット
            // ****************************
            SimpleDateFormat dateFormat = new SimpleDateFormat("yyyy/MM/dd");
            cell( sheet, 3, 3, dateFormat.parse("2020/11/27") );

            // ****************************
            // 値のセット
            // ****************************
            cell( sheet, 4, 3, 1000 );
            cell( sheet, 5, 3, 1234567890 );
            cell( sheet, 6, 3, "日本語" );
            cell( sheet, 7, 3, "ABCDEFG abcdefg" );

            // ****************************
            // 式のセット
            // ****************************
            getCell( sheet, 8, 3 ).setCellFormula( "A1" );

            // ****************************
            // 罫線
            // ****************************
            cell( sheet, 3, 3, 10, 5, BorderStyle.DOUBLE );

            // ****************************
            // セルの値を表示
            // ****************************
            for (int i = 1; i <= 10; i++)
            {
                System.out.println( cell( sheet, i, 3 ) );
            }

            // ****************************
            // 書き込み用のファイルストリーム
            // ****************************
            FileOutputStream fos = new FileOutputStream("sample.xlsx");
            
            // ****************************
            // 保存と終了
            // ****************************
            book.write(fos);
            book.close();

        } catch (Exception e) {

            e.printStackTrace();

        }

    }

    // ****************************
    // セル( XSSFCell ) を取得
    // ****************************
    static XSSFCell getCell(XSSFSheet sheet, int row, int col) {

        XSSFRow xslRow = sheet.getRow(row - 1);
        if ( xslRow == null ) {
            // 行を作成
            xslRow = sheet.createRow( row - 1 );
        }

        XSSFCell cell = xslRow.getCell( col - 1 );
        if ( cell == null ) {
            // セルを作成
            cell = xslRow.createCell( col - 1 );
        }
        return cell;

    }
    // ****************************
    // セルに書き込む
    // ****************************
    // 文字列
    static void cell(XSSFSheet sheet, int row, int col, String value) {

        XSSFCell cell = getCell(sheet, row, col);
        cell.setCellValue(value);

    }
    // 数値
    static void cell(XSSFSheet sheet, int row, int col, double value) {

        XSSFCell cell = getCell(sheet, row, col);
        cell.setCellValue(value);

    }
    // 日付 : BuiltinFormats で定義された値(14) を使用
    static void cell(XSSFSheet sheet, int row, int col, Date value) {

        XSSFCell cell = getCell(sheet, row, col);
        XSSFCellStyle style = sheet.getWorkbook().createCellStyle();
        // Class BuiltinFormats より "m/d/yy"
        style.setDataFormat(14);
        cell.setCellStyle(style);
        cell.setCellValue(value);

    }
    
    // ****************************
    // セル読み込む
    // ****************************
    static String cell(XSSFSheet sheet, int row, int col) {

        XSSFRow xslRow = sheet.getRow(row - 1);
        if ( xslRow == null ) {
            return "";
        }

        XSSFCell cell = xslRow.getCell( col - 1 );
        if ( cell == null ) {
            return "";
        }

        CellType type = cell.getCellType();
        // 文字列
        if ( type == CellType.STRING ) {
            return cell.getStringCellValue();
        } 
        if ( type == CellType.NUMERIC ) {
            // 日付
            if( org.apache.poi.ss.usermodel.DateUtil.isCellDateFormatted(cell) ) {
                SimpleDateFormat sdf = new SimpleDateFormat( "yyyy/MM/dd HH:mm:ss" );
                return sdf.format( cell.getDateCellValue() );
            }
            // 数値
            else {
                return String.format("%f", cell.getNumericCellValue());
            }
        } 
        // 式
        if ( type == CellType.FORMULA ) {
            return cell.getCellFormula();
        }
        
        String result = cell.getRawValue();
        if ( result == null ) {
            result = "";
        }

        return result;

    }

    // ****************************
    // セルの幅
    // ****************************
    static void cellWidth(XSSFSheet sheet, int col, int width) {

        sheet.setColumnWidth(col-1, width);

    }

    // ****************************
    // セルの結合
    // ****************************
    static void cell(XSSFSheet sheet, int row1, int col1, int row2, int col2) {

        sheet.addMergedRegion( new CellRangeAddress(row1-1, row2-1, col1-1, col2-1) );

    }

    // ****************************
    // 範囲の外側の罫線
    // ****************************
    static void cell(XSSFSheet sheet, int row1, int col1, int row2, int col2, BorderStyle borderStyle ) {

        CellRangeAddress region = new CellRangeAddress(row1-1, row2-1, col1-1, col2-1);

        RegionUtil.setBorderTop( borderStyle, region, sheet );
        RegionUtil.setBorderBottom( borderStyle, region, sheet );
        RegionUtil.setBorderLeft( borderStyle, region, sheet );
        RegionUtil.setBorderRight( borderStyle, region, sheet );

    }

}

実行結果

読込みは以下のような感じで

XSSFWorkbook book = XSSFWorkbookFactory.createWorkbook(new FileInputStream("sample.xlsx"));

関連する記事

JScript : Excel の新しいブックのデフォルトのシートのセルに直接値をセットして、オートフィルを Range オブジェクトから実行する C# : Excel の新しいブックのデフォルトのシートのセルに直接値をセットして、オートフィルを Range オブジェクトから実行する Python : Excel の新しいブックのデフォルトのシートのセルに直接値をセットして、オートフィルを Range オブジェクトから実行する
Excel, Java

Java8 : ArrayList と 配列

単純な配列定義とデータ作成と表示

まずは配列の作成です。型として int ( プリミティブ )、String ( 文字列クラス )、User ( ユーザ作成クラス )の三種類でそれぞれ配列を作成してデータをセットして表示しています。データのセット方法としては、ループで配列一つ一つにセットする方法と、初期化子を使う方法と二つです。

表示には拡張 for を使用しています。

▼ 出力結果
0,1,2,
0,1,2,
a,b,c,
a,b,c,
a,b,c,
a,b,c,
【ASCIIコード表

public class Main {

	// 適当なユーザクラス
	static class User {
		public String stringValue; 
		public User(String stringValue) {
			this.stringValue = stringValue;
		}
	}

	public static void main(String[] args) {

		// new で配列を作成する場合の配列の数(サイズ)
		int numArray = 3;

		// ********************************
		// プリミティブ
		// ********************************
		int[] arrayBasicInt = new int[numArray];
		for( int i = 0; i < numArray; i++) {
			arrayBasicInt[i] = i;
		}
		for (int value : arrayBasicInt) {
			System.out.print(String.format("%d,",value));
		}
		
		System.out.println();
		
		// ********************************
		// プリミティブの初期化
		// ********************************
		int[] arrayInitInt = {0,1,2};
		for (int value : arrayInitInt) {
			System.out.print(String.format("%d,",value));
		}

		System.out.println();
		
		// ********************************
		// クラス
		// ********************************
		String[] arrayBasicString = new String[numArray];
		for( int i = 0; i < numArray; i++) {
			arrayBasicString[i] = String.format("%c", i+97);
		}
		for (String value : arrayBasicString) {
			System.out.print(String.format("%s,",value));
		}

		System.out.println();
		
		// ********************************
		// クラスの初期化
		// ********************************
		String[] arrayInitString = {"a","b","c"};
		for (String value : arrayInitString) {
			System.out.print(String.format("%s,",value));
		}

		System.out.println();

		// ********************************
		// 一般クラスの
		// ********************************
		User[] arrayBasicUser = new User[numArray];
		for( int i = 0; i < numArray; i++) {
			arrayBasicUser[i] = new User(String.format("%c", i+97));
		}
		for (User value : arrayBasicUser) {
			System.out.print(String.format("%s,",value.stringValue));
		}

		System.out.println();
		
		// ********************************
		// 一般クラスの初期化
		// ********************************
		User[] arrayInitUser = {new User("a"),new User("b"),new User("c")};
		for (User value : arrayInitUser) {
			System.out.print(String.format("%s,",value.stringValue));
		}
		
	}

}


配列から ArrayList

いずれも、複数のデータを一つの型の中に持つ事ができる方法ですが、配列は作成された後変更する事ができないので、自分自身で実装する場合、通常は ArrayList に変換して使用する事になります。

Arrays.asList というクラスメソッドを用いて配列は List 型に変換できます。但し、そのままでは本来の目的である変更可能なコレクションでは無いので ArrayList のコンストラクタに再度渡して利用に値する ArrayList を取得します。

また、ArrayList には、forEach メソッドを使って一覧処理が可能です。拡張 for でも可能ですが、Map 型も同様に扱う事ができるので、最初は forEach で処理を作成しましょう。

▼ 出力結果
[令, 和, 元, 年]
[令, 和, 元, 年]
[令, 和, 元, 年]
令,和,元,年,
令,和,元,年,
import java.util.ArrayList;
import java.util.Arrays;
import java.util.List;

public class ListCheck {

	public static void main(String[] args) {
		
		// ********************************
		// クラスの初期化
		// ********************************
		String[] arrayInitString = {"令","和","元","年"};
		System.out.println(Arrays.toString(arrayInitString));
		
		// ********************************
		// ArrayList に変換
		// ********************************
		List<String> interFace = Arrays.asList(arrayInitString);
		
		// ********************************
		// ① List を インターフェイス
		// に持つ ArrayList は List 型の
		// 変数に格納できる
		// ********************************

		// ********************************
		// ② Arrays.asList で取得された
		// List は 固定で変更できない
		// ( 配列と同じ特性 )
		// ********************************



		ArrayList<String> arrayListString = new ArrayList<String>(Arrays.asList(arrayInitString));
		System.out.println(arrayListString.toString());

		// ********************************
		// ③ 変更可能に変換する為に再度
		// ArrayList のコンストラクタへ
		// 渡して ArrayList を取得する
		// ********************************
	
	
	
		String[] arrayRebuildString = arrayListString.toArray(new String[0]);
		System.out.println(Arrays.toString(arrayRebuildString));

		// ********************************
		// ④ toArray メソッドで配列を
		// 作り直す事ができます
		// ********************************

	
	
		int size = arrayListString.size();
		for( int i = 0; i < size; i++ ) {
			String stringValue = String.format("%s,", arrayListString.get(i) );
			System.out.print(stringValue);
		}
		System.out.println();

		// ********************************
		// ⑤ ArrayList のメソッドを使用
		// してデータを取り出す
		// ********************************



		arrayListString.forEach(stringValue -> {
			stringValue = String.format("%s,", stringValue );
			System.out.print(stringValue);
		});
		System.out.println();

		// ********************************
		// ⑥ forEachメソッド を使用して
		// 結果をラムダ式で記述する
		// ********************************

		// ********************************
		// ⑦ HashMap の forEachメソッド
		// では、渡す値が二つになり、
		// かっこでくくる必要があります
		// ********************************

	}

}


ArrayList から配列の変換は、toArray メソッドで容易に行えます。


▼ 参考記事

配列の宣言・生成 ( Javaの道 )

配列とListの変換 ( 侍エンジニア塾ブログ )

toArray ( Oracle ArrayList )

Arrays.asList ( Oracle ) / fill / toString

Arrays.asList の罠 ( Qiita )

List⇔配列の相互変換 ( 侍エンジニア塾ブログ )

Java8のforEachとラムダ式を配列、List、Mapで使う ( 侍エンジニア塾ブログ )

拡張for文とJava8のforEachの使い方( 侍エンジニア塾ブログ )

インナークラス・メンバークラス ( Qiita )





WindowBuilder( SWT ) : テキストファイルを読み込む

WindowBuilder のインストールとプロジェクトの作成は 『Pleiades Eclipse 4.7 Oxygen : SWT(Table) + MySQL の SQL(SELECT) で一覧表示』を参照して下さい。

C# と同時並行で Java を勉強するのならば、WindowBuilder がおすすめです。JavaFX は情報が少なすぎるのでプロになってから使えばいいと思います。Java そのものの学習には、これと AndroidStudio で簡単なスマホアプリを作れば十分です。

import java.io.BufferedReader;
import java.io.FileInputStream;
import java.io.InputStreamReader;

import org.eclipse.jface.window.ApplicationWindow;
import org.eclipse.swt.SWT;
import org.eclipse.swt.events.SelectionAdapter;
import org.eclipse.swt.events.SelectionEvent;
import org.eclipse.swt.graphics.Point;
import org.eclipse.swt.widgets.Button;
import org.eclipse.swt.widgets.Composite;
import org.eclipse.swt.widgets.Control;
import org.eclipse.swt.widgets.Display;
import org.eclipse.swt.widgets.FileDialog;
import org.eclipse.swt.widgets.MessageBox;
import org.eclipse.swt.widgets.Shell;
import org.eclipse.swt.widgets.Text;

public class FormOpenText extends ApplicationWindow {
	private Text text;

	// *********************************
	// コンストラクタ
	// *********************************
	public FormOpenText() {
		super(null);
		createActions();
	}

	// *********************************
	// コントロールの追加
	// ※ Design での変更が反映されます
	// *********************************
	@Override
	protected Control createContents(Composite parent) {
		Composite container = new Composite(parent, SWT.NONE);

		// *********************************
		// ボタン
		// *********************************
		Button btnNewButton = new Button(container, SWT.NONE);
		btnNewButton.addSelectionListener(new SelectionAdapter() {
			@Override
			public void widgetSelected(SelectionEvent e) {

				// *********************************
				// ボタンのイベント
				// *********************************
				MessageBox mb = new MessageBox((Shell) parent, SWT.OK|SWT.CANCEL);
				mb.setText("テキスト");
				mb.setMessage("メッセージ");

				int result = mb.open();
				if (result == SWT.OK ) {

					System.out.println("OK");

					String path = "c:\\User";
					String[] filterExt = { "*.txt;*.csv;*.log", "*.*" };
					String[] filterNames = { "テキストファイル", "全て" };

					FileDialog fd = new FileDialog((Shell) parent,SWT.OPEN);
					fd.setFilterPath(path);
					// https://www.programcreek.com/java-api-examples/?class=org.eclipse.swt.widgets.FileDialog&method=setFilterExtensions
					fd.setFilterExtensions(filterExt);
					fd.setFilterNames(filterNames);

					String target = fd.open();
					if (target != null) {
						try {
							BufferedReader buffer = new BufferedReader(
									new InputStreamReader(
											new FileInputStream(target),
											"SJIS"));

							// 一行ぶんの文字列
							StringBuilder textData = new StringBuilder();
							String line_buffer;

							while ( null != (line_buffer = buffer.readLine() ) ) {
								// メモリルに出力
								textData.append( line_buffer + "\r\n" );
							}

							buffer.close();

							// 画面のテキストエリアにセット
							text.setText(textData.toString());

						} catch (Exception ex) {
							ex.printStackTrace();
						}
					}
				}
				if (result == SWT.CANCEL ) {
					System.out.println("CANCEL");
				}
			}
		});
		btnNewButton.setBounds(10, 10, 75, 25);
		btnNewButton.setText("New Button");

		// *********************************
		// テキストエリア
		// *********************************
		text = new Text(container, SWT.BORDER | SWT.H_SCROLL | SWT.V_SCROLL | SWT.CANCEL | SWT.MULTI);
		text.setBounds(10, 47, 414, 200);

		return container;
	}

	// *********************************
	// 初期処理
	// *********************************
	private void createActions() {

	}

	// *********************************
	// 開始
	// *********************************
	public static void main(String args[]) {
		try {
			FormOpenText window = new FormOpenText();
			window.setBlockOnOpen(true);
			window.open();
			Display.getCurrent().dispose();
		} catch (Exception e) {
			e.printStackTrace();
		}
	}

	// *********************************
	// アプリケーションウインドウ設定
	// *********************************
	@Override
	protected void configureShell(Shell newShell) {
		super.configureShell(newShell);
		newShell.setText("New Application");
	}

	// *********************************
	// Window サイズの初期設定
	// ********************************
	@Override
	protected Point getInitialSize() {
		return new Point(450, 300);
	}
}





Java の基本的なテキストファイルアクセス

FileInputStream, InputStreamReader, BufferedReader を使用して SHIFT_JIS のテキストファイルをすべて読み込んで StringBuilder にデータとして保存してからコンソール画面に出力します。

FileInputStream はファイルのオープンにあたり、ドキュメントではバイトストリームの接続を開くという説明になっています。同様に InputStreamReader『バイト・ストリームから文字ストリームへの橋渡し』という説明です。なので、このクラスでキャラクタセットを指定します。( 使用可能なキャラクタセットはこちらで確認します )

BufferedReader はその名前の通り行をバッファリングする事が目的となります。なのでメソッドは行に対するアクセスが可能となっています。
package console_01;

import java.io.BufferedReader;
import java.io.FileInputStream;
import java.io.InputStreamReader;

public class Main {

	public static void main(String[] args) {

		System.out.println("SJIS 単純読込");

		String currentPath;

		currentPath = System.getProperty("user.dir");

		System.out.println(currentPath);

		String target = String.format("%s\\sjis_base.txt", currentPath);
		// 読み込むファイルのパス
		System.out.println(target);

		try {
			// 接続を開く( バイトストリーム )
			FileInputStream sjis_file = new FileInputStream(target);

			// バイト・ストリームから文字ストリームへの橋渡し
			// https://docs.oracle.com/javase/jp/8/docs/technotes/guides/intl/encoding.doc.html
			InputStreamReader charset_stream = new InputStreamReader(sjis_file, "SJIS");

			// 行をバッファリング
			BufferedReader buffer = new BufferedReader(charset_stream);

			// 一行ぶんの文字列
			String line_buffer;
			StringBuilder all_string = new StringBuilder();

			while ( null != (line_buffer = buffer.readLine() ) ) {
				// コマンドプロンプトに表示
				all_string.append(line_buffer);
				all_string.append("\r\n");
			}

			// 行バッファを閉じる
			buffer.close();
			// 文字ストリームを閉じる
			charset_stream.close();
			// 接続を閉じる
			sjis_file.close();

			System.out.println(all_string);


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

	}

}


以下では SHIFT_JIS で読み出したテキストデータを UTF8N のフォーマットで書き出します。メモリとしては行バッファのみを定義しており、変数を使わずに入力用と出力用のオブジェクトを一気に作成して処理しています。
package console_02;

import java.io.BufferedReader;
import java.io.BufferedWriter;
import java.io.FileInputStream;
import java.io.FileOutputStream;
import java.io.InputStreamReader;
import java.io.OutputStreamWriter;

public class Main {

	public static void main(String[] args) {

		System.out.println("SJIS > UTF8N 書込");

		String currentPath;

		currentPath = System.getProperty("user.dir");

		System.out.println(currentPath);

		// 読み込むファイルのパス
		String target = String.format("%s\\sjis_base.txt", currentPath);
		System.out.println(target);

		// 書き込むファイルのパス
		String utf8n = String.format("%s\\utf8n.txt", currentPath);
		System.out.println(utf8n);

		try {
			// 入力行をバッファリング
			BufferedReader buffer =
				new BufferedReader(
					new InputStreamReader(
						new FileInputStream(target), 
						"SJIS"
					)
				);

			// 出力用バッファリング
			BufferedWriter buffer_write = new BufferedWriter(
					new OutputStreamWriter(
						new FileOutputStream(utf8n),
						"UTF8"
					) 
				);			
			// ※ UTF8 で UTF8N となるので、UTF8 にするには先頭に BOM を出力する
			// fileOutputStream.write( 0xef );
			// fileOutputStream.write( 0xbb );
			// fileOutputStream.write( 0xbf );

			// 一行ぶんの文字列
			String line_buffer;

			while ( null != (line_buffer = buffer.readLine() ) ) {
				// ファイルに出力
				buffer_write.write( line_buffer + "\r\n" );
			}

			// バッファを閉じる
			buffer_write.close();
			buffer.close();


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

	}

}





Pleiades Eclipse 4.7 Oxygen : SWT(Table) + MySQL の SQL(SELECT) で一覧表示



WindowBuilder のインストール

SWT と Swing に関しては、WindowBuilder のサイト よりインストール用の URL を取得します。

※ バージョンは、WindowBuilder のバージョンです。(Eclipse のバージョンに依存しなくなりました)

この URL を『新規ソフトウェアのインストール』で表示されるダイアログに入力します


以前の WindowBuilder のアンインストールは、『ヘルプメニュー』>『Eclipse について』>『インストール詳細』で表示されるウインドウからアンインストールします
プロジェクト作成 プロジェクトは専用のものを使いますので、『その他』から以下を選択して下さい。 プロジェクトを作成したら、CTRL+N でその他より、以下を選択して下さい。 実行してウインドウが表示されたら準備完了です。 テンプレートの修正 メニューバー・タスクバー・ツールバー用のテンプレートは邪魔なだけなので削除します。 MySQL 接続用ライブラリのインストール Download Connector/J から jar をダウンロードして使用するか、Maven Repository より pom.xml に記述する内容を取得して使用します。 バージョンは、ここでは 5.1.46 を使用しています ( ダウンロードページでは、Looking for previous GA versions? リンクをクリックします ) Maven を使用するには、既存のプロジェクトを変換するのが簡単です。 ( プロジェクトを右クリックして『構成』から Maven プロジェクトへの変換 ) Chapter 4 Connector/J Examples 実行ソースコード
package mysql;

import java.sql.DriverManager;
import java.sql.ResultSet;
import java.sql.SQLException;
import java.text.SimpleDateFormat;

import org.eclipse.jface.window.ApplicationWindow;
import org.eclipse.swt.SWT;
import org.eclipse.swt.events.SelectionAdapter;
import org.eclipse.swt.events.SelectionEvent;
import org.eclipse.swt.graphics.Point;
import org.eclipse.swt.widgets.Button;
import org.eclipse.swt.widgets.Composite;
import org.eclipse.swt.widgets.Control;
import org.eclipse.swt.widgets.Display;
import org.eclipse.swt.widgets.Shell;
import org.eclipse.swt.widgets.Table;
import org.eclipse.swt.widgets.TableColumn;
import org.eclipse.swt.widgets.TableItem;

import com.mysql.jdbc.Connection;
import com.mysql.jdbc.ResultSetMetaData;
import com.mysql.jdbc.Statement;

public class Main extends ApplicationWindow {

	// https://help.eclipse.org/neon/index.jsp?topic=%2Forg.eclipse.platform.doc.isv%2Freference%2Fapi%2Findex.html&org/eclipse/swt/widgets/Table.html
	private Table table;

	// https://mvnrepository.com/artifact/mysql/mysql-connector-java/5.1.46
	// https://dev.mysql.com/doc/connector-j/5.1/en/connector-j-examples.html
	private Connection conn = null;
	private Statement stmt = null;
	private ResultSet rs = null;
	private int maxRows = 20;

	public Main() {
		super(null);
		createActions();
	}

	@Override
	protected Control createContents(Composite parent) {
		Composite container = new Composite(parent, SWT.NONE);

		table = new Table(container, SWT.BORDER | SWT.FULL_SELECTION);
		table.setBounds(10, 41, 764, 338);
		table.setHeaderVisible(true);
		table.setLinesVisible(true);

		Button button = new Button(container, SWT.NONE);
		button.addSelectionListener(new SelectionAdapter() {
			@Override
			public void widgetSelected(SelectionEvent e) {
				// 行を全て削除
				table.removeAll();
				loadMySQL("select * from 社員マスタ");
			}

		});
		button.setBounds(10, 10, 75, 25);
		button.setText("実行");

		return container;
	}

	private void createActions() {
		// Create the actions
	}

	public static void main(String args[]) {
		try {
			Main window = new Main();
			window.setBlockOnOpen(true);
			window.open();
			Display.getCurrent().dispose();
		} catch (Exception e) {
			e.printStackTrace();
		}
	}

	@Override
	protected void configureShell(Shell newShell) {
		super.configureShell(newShell);
		newShell.setText("MySQL Connector/J");
	}

	@Override
	protected Point getInitialSize() {
		return new Point(800, 443);
	}


	private void loadMySQL( String sql ) {

		try {
			// MySQL Connector/J 接続
			conn = (Connection) DriverManager.getConnection(
				"jdbc:mysql://localhost/lightbox?user=root&password="
			);

			stmt = (Statement) conn.createStatement();
			rs = stmt.executeQuery(sql);

			// select の結果の列情報の取得
			ResultSetMetaData rsmd = (ResultSetMetaData) rs.getMetaData();

			// 列数
			int columnCount = rsmd.getColumnCount();

			// 前回のテーブル列を全て削除
			int tableColumnCount = table.getColumnCount();
			TableColumn tableColumnWork = null;
			for( int i = tableColumnCount - 1; i >= 0; i--) {
				tableColumnWork = table.getColumn(i);
				tableColumnWork.dispose();
			}

			// 列名
			TableColumn tableColumn = null;
			for( int i = 1; i <= columnCount; i++) {
				tableColumn = new TableColumn(table, SWT.NONE);
				tableColumn.setWidth(100);
				tableColumn.setText(rsmd.getColumnName(i));
			}

			TableItem tableItem = null;
			SimpleDateFormat sdf = new SimpleDateFormat("yyyy/MM/dd");
			int countRow = 0;
			while( rs.next() && countRow < maxRows ) {

				countRow++;

				String[] columnData = new String[columnCount];

				for( int i = 1; i <= columnCount; i++) {

					if ( rsmd.getColumnTypeName(i).equals("DATETIME") ) {
						columnData[i-1] = sdf.format(rs.getDate(i));
					}
					else {
						columnData[i-1] = rs.getString(i);
					}

				}
				tableItem = new TableItem(table, SWT.NONE);
				tableItem.setText(columnData);
			}

			rs.close();
			stmt.close();
			conn.close();

		} catch (SQLException ex) {
			// handle any errors
			System.out.println("SQLException: " + ex.getMessage());
			System.out.println("SQLState: " + ex.getSQLState());
			System.out.println("VendorError: " + ex.getErrorCode());
		}

	}
}




pom.xml
<project xmlns="http://maven.apache.org/POM/4.0.0" xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance" xsi:schemaLocation="http://maven.apache.org/POM/4.0.0 http://maven.apache.org/xsd/maven-4.0.0.xsd">
  <modelVersion>4.0.0</modelVersion>
  <groupId>MySQL_01</groupId>
  <artifactId>MySQL_01</artifactId>
  <version>0.0.1-SNAPSHOT</version>
  <build>
    <sourceDirectory>src</sourceDirectory>
    <plugins>
      <plugin>
        <artifactId>maven-compiler-plugin</artifactId>
        <version>3.7.0</version>
        <configuration>
          <source>1.8</source>
          <target>1.8</target>
        </configuration>
      </plugin>
    </plugins>
  </build>
  <dependencies>
    <dependency>
      <groupId>mysql</groupId>
      <artifactId>mysql-connector-java</artifactId>
      <version>5.1.46</version>
    </dependency>
  </dependencies>

</project>


関連する記事

WindowBuilder のテーブルコントロールにインターネットから JSON データを読み込んで処理するテンプレート ( 行データをダブルクリックして取得 )