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

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

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

サンプル

オーバーロードを使用して、できるだけ cell というメソッドでできるようにしてみました。Microsoft の仕様に合わせて行や列を 1 始まりにしたかったという意図もあります。
001.import java.io.FileOutputStream;
002.import java.text.SimpleDateFormat;
003.import java.util.Date;
004. 
005.import org.apache.poi.ss.usermodel.BorderStyle;
006.import org.apache.poi.ss.usermodel.CellType;
007.import org.apache.poi.ss.util.CellRangeAddress;
008.import org.apache.poi.ss.util.RegionUtil;
009.import org.apache.poi.xssf.usermodel.XSSFCell;
010.import org.apache.poi.xssf.usermodel.XSSFCellStyle;
011.import org.apache.poi.xssf.usermodel.XSSFRow;
012.import org.apache.poi.xssf.usermodel.XSSFSheet;
013.import org.apache.poi.xssf.usermodel.XSSFWorkbook;
014.import org.apache.poi.xssf.usermodel.XSSFWorkbookFactory;
015. 
016.public class Main {
017. 
018.    private static XSSFWorkbook book;
019.    private static XSSFSheet  sheet;
020. 
021.    // *****************************************************
022.    // エントリポイント
023.    // *****************************************************
024.    public static void main(String[] args) {
025.        try {
026.            // ****************************
027.            // ブック作成
028.            // ****************************
029.            book = XSSFWorkbookFactory.createWorkbook();
030. 
031.            // ****************************
032.            // シート作成
033.            // ****************************
034.            sheet = book.createSheet("Javaの処理");
035. 
036.            // ****************************
037.            // セルに値を直接セット
038.            // ****************************
039.            for (int i = 1; i <= 10; i++)
040.            {
041.                cell( sheet, i, 1, String.format("処理 : %d", i ));
042.            }
043. 
044.            // ****************************
045.            // セルの幅( 3列目 )
046.            // ****************************
047.            cellWidth( sheet, 3, 6000 );
048. 
049.            // ****************************
050.            // セルの結合
051.            // ****************************
052.            cell( sheet, 1, 3, 1, 5 );
053.            // 結合されたセルに値をセット
054.            cell( sheet, 1, 3, "結合されたセル" );
055.             
056.            // ****************************
057.            // 日付のセット
058.            // ****************************
059.            SimpleDateFormat dateFormat = new SimpleDateFormat("yyyy/MM/dd");
060.            cell( sheet, 3, 3, dateFormat.parse("2020/11/27") );
061. 
062.            // ****************************
063.            // 値のセット
064.            // ****************************
065.            cell( sheet, 4, 3, 1000 );
066.            cell( sheet, 5, 3, 1234567890 );
067.            cell( sheet, 6, 3, "日本語" );
068.            cell( sheet, 7, 3, "ABCDEFG abcdefg" );
069. 
070.            // ****************************
071.            // 式のセット
072.            // ****************************
073.            getCell( sheet, 8, 3 ).setCellFormula( "A1" );
074. 
075.            // ****************************
076.            // 罫線
077.            // ****************************
078.            cell( sheet, 3, 3, 10, 5, BorderStyle.DOUBLE );
079. 
080.            // ****************************
081.            // セルの値を表示
082.            // ****************************
083.            for (int i = 1; i <= 10; i++)
084.            {
085.                System.out.println( cell( sheet, i, 3 ) );
086.            }
087. 
088.            // ****************************
089.            // 書き込み用のファイルストリーム
090.            // ****************************
091.            FileOutputStream fos = new FileOutputStream("sample.xlsx");
092.             
093.            // ****************************
094.            // 保存と終了
095.            // ****************************
096.            book.write(fos);
097.            book.close();
098. 
099.        } catch (Exception e) {
100. 
101.            e.printStackTrace();
102. 
103.        }
104. 
105.    }
106. 
107.    // ****************************
108.    // セル( XSSFCell ) を取得
109.    // ****************************
110.    static XSSFCell getCell(XSSFSheet sheet, int row, int col) {
111. 
112.        XSSFRow xslRow = sheet.getRow(row - 1);
113.        if ( xslRow == null ) {
114.            // 行を作成
115.            xslRow = sheet.createRow( row - 1 );
116.        }
117. 
118.        XSSFCell cell = xslRow.getCell( col - 1 );
119.        if ( cell == null ) {
120.            // セルを作成
121.            cell = xslRow.createCell( col - 1 );
122.        }
123.        return cell;
124. 
125.    }
126.    // ****************************
127.    // セルに書き込む
128.    // ****************************
129.    // 文字列
130.    static void cell(XSSFSheet sheet, int row, int col, String value) {
131. 
132.        XSSFCell cell = getCell(sheet, row, col);
133.        cell.setCellValue(value);
134. 
135.    }
136.    // 数値
137.    static void cell(XSSFSheet sheet, int row, int col, double value) {
138. 
139.        XSSFCell cell = getCell(sheet, row, col);
140.        cell.setCellValue(value);
141. 
142.    }
143.    // 日付 : BuiltinFormats で定義された値(14) を使用
144.    static void cell(XSSFSheet sheet, int row, int col, Date value) {
145. 
146.        XSSFCell cell = getCell(sheet, row, col);
147.        XSSFCellStyle style = sheet.getWorkbook().createCellStyle();
148.        // Class BuiltinFormats より "m/d/yy"
149.        style.setDataFormat(14);
150.        cell.setCellStyle(style);
151.        cell.setCellValue(value);
152. 
153.    }
154.     
155.    // ****************************
156.    // セル読み込む
157.    // ****************************
158.    static String cell(XSSFSheet sheet, int row, int col) {
159. 
160.        XSSFRow xslRow = sheet.getRow(row - 1);
161.        if ( xslRow == null ) {
162.            return "";
163.        }
164. 
165.        XSSFCell cell = xslRow.getCell( col - 1 );
166.        if ( cell == null ) {
167.            return "";
168.        }
169. 
170.        CellType type = cell.getCellType();
171.        // 文字列
172.        if ( type == CellType.STRING ) {
173.            return cell.getStringCellValue();
174.        }
175.        if ( type == CellType.NUMERIC ) {
176.            // 日付
177.            if( org.apache.poi.ss.usermodel.DateUtil.isCellDateFormatted(cell) ) {
178.                SimpleDateFormat sdf = new SimpleDateFormat( "yyyy/MM/dd HH:mm:ss" );
179.                return sdf.format( cell.getDateCellValue() );
180.            }
181.            // 数値
182.            else {
183.                return String.format("%f", cell.getNumericCellValue());
184.            }
185.        }
186.        // 式
187.        if ( type == CellType.FORMULA ) {
188.            return cell.getCellFormula();
189.        }
190.         
191.        String result = cell.getRawValue();
192.        if ( result == null ) {
193.            result = "";
194.        }
195. 
196.        return result;
197. 
198.    }
199. 
200.    // ****************************
201.    // セルの幅
202.    // ****************************
203.    static void cellWidth(XSSFSheet sheet, int col, int width) {
204. 
205.        sheet.setColumnWidth(col-1, width);
206. 
207.    }
208. 
209.    // ****************************
210.    // セルの結合
211.    // ****************************
212.    static void cell(XSSFSheet sheet, int row1, int col1, int row2, int col2) {
213. 
214.        sheet.addMergedRegion( new CellRangeAddress(row1-1, row2-1, col1-1, col2-1) );
215. 
216.    }
217. 
218.    // ****************************
219.    // 範囲の外側の罫線
220.    // ****************************
221.    static void cell(XSSFSheet sheet, int row1, int col1, int row2, int col2, BorderStyle borderStyle ) {
222. 
223.        CellRangeAddress region = new CellRangeAddress(row1-1, row2-1, col1-1, col2-1);
224. 
225.        RegionUtil.setBorderTop( borderStyle, region, sheet );
226.        RegionUtil.setBorderBottom( borderStyle, region, sheet );
227.        RegionUtil.setBorderLeft( borderStyle, region, sheet );
228.        RegionUtil.setBorderRight( borderStyle, region, sheet );
229. 
230.    }
231. 
232.}

実行結果

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

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コード表

a は 97(0x61) からです

01.public class Main {
02. 
03.        // 適当なユーザクラス
04.        static class User {
05.                public String stringValue;
06.                public User(String stringValue) {
07.                        this.stringValue = stringValue;
08.                }
09.        }
10. 
11.        public static void main(String[] args) {
12. 
13.                // new で配列を作成する場合の配列の数(サイズ)
14.                int numArray = 3;
15. 
16.                // ********************************
17.                // プリミティブ
18.                // ********************************
19.                int[] arrayBasicInt = new int[numArray];
20.                for( int i = 0; i < numArray; i++) {
21.                        arrayBasicInt[i] = i;
22.                }
23.                for (int value : arrayBasicInt) {
24.                        System.out.print(String.format("%d,",value));
25.                }
26.                 
27.                System.out.println();
28.                 
29.                // ********************************
30.                // プリミティブの初期化
31.                // ********************************
32.                int[] arrayInitInt = {0,1,2};
33.                for (int value : arrayInitInt) {
34.                        System.out.print(String.format("%d,",value));
35.                }
36. 
37.                System.out.println();
38.                 
39.                // ********************************
40.                // クラス
41.                // ********************************
42.                String[] arrayBasicString = new String[numArray];
43.                for( int i = 0; i < numArray; i++) {
44.                        arrayBasicString[i] = String.format("%c", i+97);
45.                }
46.                for (String value : arrayBasicString) {
47.                        System.out.print(String.format("%s,",value));
48.                }
49. 
50.                System.out.println();
51.                 
52.                // ********************************
53.                // クラスの初期化
54.                // ********************************
55.                String[] arrayInitString = {"a","b","c"};
56.                for (String value : arrayInitString) {
57.                        System.out.print(String.format("%s,",value));
58.                }
59. 
60.                System.out.println();
61. 
62.                // ********************************
63.                // 一般クラスの
64.                // ********************************
65.                User[] arrayBasicUser = new User[numArray];
66.                for( int i = 0; i < numArray; i++) {
67.                        arrayBasicUser[i] = new User(String.format("%c", i+97));
68.                }
69.                for (User value : arrayBasicUser) {
70.                        System.out.print(String.format("%s,",value.stringValue));
71.                }
72. 
73.                System.out.println();
74.                 
75.                // ********************************
76.                // 一般クラスの初期化
77.                // ********************************
78.                User[] arrayInitUser = {new User("a"),new User("b"),new User("c")};
79.                for (User value : arrayInitUser) {
80.                        System.out.print(String.format("%s,",value.stringValue));
81.                }
82.                 
83.        }
84. 
85.}

配列から ArrayList

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

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

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

▼ 出力結果
[令, 和, 元, 年]
[令, 和, 元, 年]
[令, 和, 元, 年]
令,和,元,年,
令,和,元,年,
01.import java.util.ArrayList;
02.import java.util.Arrays;
03.import java.util.List;
04. 
05.public class ListCheck {
06. 
07.        public static void main(String[] args) {
08.                 
09.                // ********************************
10.                // クラスの初期化
11.                // ********************************
12.                String[] arrayInitString = {"令","和","元","年"};
13.                System.out.println(Arrays.toString(arrayInitString));
14.                 
15.                // ********************************
16.                // ArrayList に変換
17.                // ********************************
18.                List<String> interFace = Arrays.asList(arrayInitString);
19.                 
20.                // ********************************
21.                // ① List を インターフェイス
22.                // に持つ ArrayList は List 型の
23.                // 変数に格納できる
24.                // ********************************
25. 
26.                // ********************************
27.                // ② Arrays.asList で取得された
28.                // List は 固定で変更できない
29.                // ( 配列と同じ特性 )
30.                // ********************************
31. 
32. 
33. 
34.                ArrayList<String> arrayListString = new ArrayList<String>(Arrays.asList(arrayInitString));
35.                System.out.println(arrayListString.toString());
36. 
37.                // ********************************
38.                // ③ 変更可能に変換する為に再度
39.                // ArrayList のコンストラクタへ
40.                // 渡して ArrayList を取得する
41.                // ********************************
42.         
43.         
44.         
45.                String[] arrayRebuildString = arrayListString.toArray(new String[0]);
46.                System.out.println(Arrays.toString(arrayRebuildString));
47. 
48.                // ********************************
49.                // ④ toArray メソッドで配列を
50.                // 作り直す事ができます
51.                // ********************************
52. 
53.         
54.         
55.                int size = arrayListString.size();
56.                for( int i = 0; i < size; i++ ) {
57.                        String stringValue = String.format("%s,", arrayListString.get(i) );
58.                        System.out.print(stringValue);
59.                }
60.                System.out.println();
61. 
62.                // ********************************
63.                // ⑤ ArrayList のメソッドを使用
64.                // してデータを取り出す
65.                // ********************************
66. 
67. 
68. 
69.                arrayListString.forEach(stringValue -> {
70.                        stringValue = String.format("%s,", stringValue );
71.                        System.out.print(stringValue);
72.                });
73.                System.out.println();
74. 
75.                // ********************************
76.                // ⑥ forEachメソッド を使用して
77.                // 結果をラムダ式で記述する
78.                // ********************************
79. 
80.                // ********************************
81.                // ⑦ HashMap の forEachメソッド
82.                // では、渡す値が二つになり、
83.                // かっこでくくる必要があります
84.                // ********************************
85. 
86.        }
87. 
88.}

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 で簡単なスマホアプリを作れば十分です。

001.import java.io.BufferedReader;
002.import java.io.FileInputStream;
003.import java.io.InputStreamReader;
004. 
005.import org.eclipse.jface.window.ApplicationWindow;
006.import org.eclipse.swt.SWT;
007.import org.eclipse.swt.events.SelectionAdapter;
008.import org.eclipse.swt.events.SelectionEvent;
009.import org.eclipse.swt.graphics.Point;
010.import org.eclipse.swt.widgets.Button;
011.import org.eclipse.swt.widgets.Composite;
012.import org.eclipse.swt.widgets.Control;
013.import org.eclipse.swt.widgets.Display;
014.import org.eclipse.swt.widgets.FileDialog;
015.import org.eclipse.swt.widgets.MessageBox;
016.import org.eclipse.swt.widgets.Shell;
017.import org.eclipse.swt.widgets.Text;
018. 
019.public class FormOpenText extends ApplicationWindow {
020.        private Text text;
021. 
022.        // *********************************
023.        // コンストラクタ
024.        // *********************************
025.        public FormOpenText() {
026.                super(null);
027.                createActions();
028.        }
029. 
030.        // *********************************
031.        // コントロールの追加
032.        // ※ Design での変更が反映されます
033.        // *********************************
034.        @Override
035.        protected Control createContents(Composite parent) {
036.                Composite container = new Composite(parent, SWT.NONE);
037. 
038.                // *********************************
039.                // ボタン
040.                // *********************************
041.                Button btnNewButton = new Button(container, SWT.NONE);
042.                btnNewButton.addSelectionListener(new SelectionAdapter() {
043.                        @Override
044.                        public void widgetSelected(SelectionEvent e) {
045. 
046.                                // *********************************
047.                                // ボタンのイベント
048.                                // *********************************
049.                                MessageBox mb = new MessageBox((Shell) parent, SWT.OK|SWT.CANCEL);
050.                                mb.setText("テキスト");
051.                                mb.setMessage("メッセージ");
052. 
053.                                int result = mb.open();
054.                                if (result == SWT.OK ) {
055. 
056.                                        System.out.println("OK");
057. 
058.                                        String path = "c:\\User";
059.                                        String[] filterExt = { "*.txt;*.csv;*.log", "*.*" };
060.                                        String[] filterNames = { "テキストファイル", "全て" };
061. 
062.                                        FileDialog fd = new FileDialog((Shell) parent,SWT.OPEN);
063.                                        fd.setFilterPath(path);
064.                                        // https://www.programcreek.com/java-api-examples/?class=org.eclipse.swt.widgets.FileDialog&method=setFilterExtensions
065.                                        fd.setFilterExtensions(filterExt);
066.                                        fd.setFilterNames(filterNames);
067. 
068.                                        String target = fd.open();
069.                                        if (target != null) {
070.                                                try {
071.                                                        BufferedReader buffer = new BufferedReader(
072.                                                                        new InputStreamReader(
073.                                                                                        new FileInputStream(target),
074.                                                                                        "SJIS"));
075. 
076.                                                        // 一行ぶんの文字列
077.                                                        StringBuilder textData = new StringBuilder();
078.                                                        String line_buffer;
079. 
080.                                                        while ( null != (line_buffer = buffer.readLine() ) ) {
081.                                                                // メモリルに出力
082.                                                                textData.append( line_buffer + "\r\n" );
083.                                                        }
084. 
085.                                                        buffer.close();
086. 
087.                                                        // 画面のテキストエリアにセット
088.                                                        text.setText(textData.toString());
089. 
090.                                                } catch (Exception ex) {
091.                                                        ex.printStackTrace();
092.                                                }
093.                                        }
094.                                }
095.                                if (result == SWT.CANCEL ) {
096.                                        System.out.println("CANCEL");
097.                                }
098.                        }
099.                });
100.                btnNewButton.setBounds(10, 10, 75, 25);
101.                btnNewButton.setText("New Button");
102. 
103.                // *********************************
104.                // テキストエリア
105.                // *********************************
106.                text = new Text(container, SWT.BORDER | SWT.H_SCROLL | SWT.V_SCROLL | SWT.CANCEL | SWT.MULTI);
107.                text.setBounds(10, 47, 414, 200);
108. 
109.                return container;
110.        }
111. 
112.        // *********************************
113.        // 初期処理
114.        // *********************************
115.        private void createActions() {
116. 
117.        }
118. 
119.        // *********************************
120.        // 開始
121.        // *********************************
122.        public static void main(String args[]) {
123.                try {
124.                        FormOpenText window = new FormOpenText();
125.                        window.setBlockOnOpen(true);
126.                        window.open();
127.                        Display.getCurrent().dispose();
128.                } catch (Exception e) {
129.                        e.printStackTrace();
130.                }
131.        }
132. 
133.        // *********************************
134.        // アプリケーションウインドウ設定
135.        // *********************************
136.        @Override
137.        protected void configureShell(Shell newShell) {
138.                super.configureShell(newShell);
139.                newShell.setText("New Application");
140.        }
141. 
142.        // *********************************
143.        // Window サイズの初期設定
144.        // ********************************
145.        @Override
146.        protected Point getInitialSize() {
147.                return new Point(450, 300);
148.        }
149.}




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

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

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

BufferedReader はその名前の通り行をバッファリングする事が目的となります。なのでメソッドは行に対するアクセスが可能となっています。
01.package console_01;
02. 
03.import java.io.BufferedReader;
04.import java.io.FileInputStream;
05.import java.io.InputStreamReader;
06. 
07.public class Main {
08. 
09.        public static void main(String[] args) {
10. 
11.                System.out.println("SJIS 単純読込");
12. 
13.                String currentPath;
14. 
15.                currentPath = System.getProperty("user.dir");
16. 
17.                System.out.println(currentPath);
18. 
19.                String target = String.format("%s\\sjis_base.txt", currentPath);
20.                // 読み込むファイルのパス
21.                System.out.println(target);
22. 
23.                try {
24.                        // 接続を開く( バイトストリーム )
25.                        FileInputStream sjis_file = new FileInputStream(target);
26. 
27.                        // バイト・ストリームから文字ストリームへの橋渡し
28.                        // https://docs.oracle.com/javase/jp/8/docs/technotes/guides/intl/encoding.doc.html
29.                        InputStreamReader charset_stream = new InputStreamReader(sjis_file, "SJIS");
30. 
31.                        // 行をバッファリング
32.                        BufferedReader buffer = new BufferedReader(charset_stream);
33. 
34.                        // 一行ぶんの文字列
35.                        String line_buffer;
36.                        StringBuilder all_string = new StringBuilder();
37. 
38.                        while ( null != (line_buffer = buffer.readLine() ) ) {
39.                                // コマンドプロンプトに表示
40.                                all_string.append(line_buffer);
41.                                all_string.append("\r\n");
42.                        }
43. 
44.                        // 行バッファを閉じる
45.                        buffer.close();
46.                        // 文字ストリームを閉じる
47.                        charset_stream.close();
48.                        // 接続を閉じる
49.                        sjis_file.close();
50. 
51.                        System.out.println(all_string);
52. 
53. 
54.                } catch (Exception e) {
55.                        e.printStackTrace();
56.                }
57. 
58.        }
59. 
60.}

以下では SHIFT_JIS で読み出したテキストデータを UTF8N のフォーマットで書き出します。メモリとしては行バッファのみを定義しており、変数を使わずに入力用と出力用のオブジェクトを一気に作成して処理しています。
01.package console_02;
02. 
03.import java.io.BufferedReader;
04.import java.io.BufferedWriter;
05.import java.io.FileInputStream;
06.import java.io.FileOutputStream;
07.import java.io.InputStreamReader;
08.import java.io.OutputStreamWriter;
09. 
10.public class Main {
11. 
12.        public static void main(String[] args) {
13. 
14.                System.out.println("SJIS > UTF8N 書込");
15. 
16.                String currentPath;
17. 
18.                currentPath = System.getProperty("user.dir");
19. 
20.                System.out.println(currentPath);
21. 
22.                // 読み込むファイルのパス
23.                String target = String.format("%s\\sjis_base.txt", currentPath);
24.                System.out.println(target);
25. 
26.                // 書き込むファイルのパス
27.                String utf8n = String.format("%s\\utf8n.txt", currentPath);
28.                System.out.println(utf8n);
29. 
30.                try {
31.                        // 入力行をバッファリング
32.                        BufferedReader buffer =
33.                                new BufferedReader(
34.                                        new InputStreamReader(
35.                                                new FileInputStream(target),
36.                                                "SJIS"
37.                                        )
38.                                );
39. 
40.                        // 出力用バッファリング
41.                        BufferedWriter buffer_write = new BufferedWriter(
42.                                        new OutputStreamWriter(
43.                                                new FileOutputStream(utf8n),
44.                                                "UTF8"
45.                                        )
46.                                );                     
47.                        // ※ UTF8 で UTF8N となるので、UTF8 にするには先頭に BOM を出力する
48.                        // fileOutputStream.write( 0xef );
49.                        // fileOutputStream.write( 0xbb );
50.                        // fileOutputStream.write( 0xbf );
51. 
52.                        // 一行ぶんの文字列
53.                        String line_buffer;
54. 
55.                        while ( null != (line_buffer = buffer.readLine() ) ) {
56.                                // ファイルに出力
57.                                buffer_write.write( line_buffer + "\r\n" );
58.                        }
59. 
60.                        // バッファを閉じる
61.                        buffer_write.close();
62.                        buffer.close();
63. 
64. 
65.                } catch (Exception e) {
66.                        e.printStackTrace();
67.                }
68. 
69.        }
70. 
71.}




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

実行ソースコード

001.package mysql;
002. 
003.import java.sql.DriverManager;
004.import java.sql.ResultSet;
005.import java.sql.SQLException;
006.import java.text.SimpleDateFormat;
007. 
008.import org.eclipse.jface.window.ApplicationWindow;
009.import org.eclipse.swt.SWT;
010.import org.eclipse.swt.events.SelectionAdapter;
011.import org.eclipse.swt.events.SelectionEvent;
012.import org.eclipse.swt.graphics.Point;
013.import org.eclipse.swt.widgets.Button;
014.import org.eclipse.swt.widgets.Composite;
015.import org.eclipse.swt.widgets.Control;
016.import org.eclipse.swt.widgets.Display;
017.import org.eclipse.swt.widgets.Shell;
018.import org.eclipse.swt.widgets.Table;
019.import org.eclipse.swt.widgets.TableColumn;
020.import org.eclipse.swt.widgets.TableItem;
021. 
022.import com.mysql.jdbc.Connection;
023.import com.mysql.jdbc.ResultSetMetaData;
024.import com.mysql.jdbc.Statement;
025. 
026.public class Main extends ApplicationWindow {
027. 
028.        // https://help.eclipse.org/neon/index.jsp?topic=%2Forg.eclipse.platform.doc.isv%2Freference%2Fapi%2Findex.html&org/eclipse/swt/widgets/Table.html
029.        private Table table;
030. 
031.        // https://mvnrepository.com/artifact/mysql/mysql-connector-java/5.1.46
032.        // https://dev.mysql.com/doc/connector-j/5.1/en/connector-j-examples.html
033.        private Connection conn = null;
034.        private Statement stmt = null;
035.        private ResultSet rs = null;
036.        private int maxRows = 20;
037. 
038.        public Main() {
039.                super(null);
040.                createActions();
041.        }
042. 
043.        @Override
044.        protected Control createContents(Composite parent) {
045.                Composite container = new Composite(parent, SWT.NONE);
046. 
047.                table = new Table(container, SWT.BORDER | SWT.FULL_SELECTION);
048.                table.setBounds(10, 41, 764, 338);
049.                table.setHeaderVisible(true);
050.                table.setLinesVisible(true);
051. 
052.                Button button = new Button(container, SWT.NONE);
053.                button.addSelectionListener(new SelectionAdapter() {
054.                        @Override
055.                        public void widgetSelected(SelectionEvent e) {
056.                                // 行を全て削除
057.                                table.removeAll();
058.                                loadMySQL("select * from 社員マスタ");
059.                        }
060. 
061.                });
062.                button.setBounds(10, 10, 75, 25);
063.                button.setText("実行");
064. 
065.                return container;
066.        }
067. 
068.        private void createActions() {
069.                // Create the actions
070.        }
071. 
072.        public static void main(String args[]) {
073.                try {
074.                        Main window = new Main();
075.                        window.setBlockOnOpen(true);
076.                        window.open();
077.                        Display.getCurrent().dispose();
078.                } catch (Exception e) {
079.                        e.printStackTrace();
080.                }
081.        }
082. 
083.        @Override
084.        protected void configureShell(Shell newShell) {
085.                super.configureShell(newShell);
086.                newShell.setText("MySQL Connector/J");
087.        }
088. 
089.        @Override
090.        protected Point getInitialSize() {
091.                return new Point(800, 443);
092.        }
093. 
094. 
095.        private void loadMySQL( String sql ) {
096. 
097.                try {
098.                        // MySQL Connector/J 接続
099.                        conn = (Connection) DriverManager.getConnection(
100.                                "jdbc:mysql://localhost/lightbox?user=root&password="
101.                        );
102. 
103.                        stmt = (Statement) conn.createStatement();
104.                        rs = stmt.executeQuery(sql);
105. 
106.                        // select の結果の列情報の取得
107.                        ResultSetMetaData rsmd = (ResultSetMetaData) rs.getMetaData();
108. 
109.                        // 列数
110.                        int columnCount = rsmd.getColumnCount();
111. 
112.                        // 前回のテーブル列を全て削除
113.                        int tableColumnCount = table.getColumnCount();
114.                        TableColumn tableColumnWork = null;
115.                        for( int i = tableColumnCount - 1; i >= 0; i--) {
116.                                tableColumnWork = table.getColumn(i);
117.                                tableColumnWork.dispose();
118.                        }
119. 
120.                        // 列名
121.                        TableColumn tableColumn = null;
122.                        for( int i = 1; i <= columnCount; i++) {
123.                                tableColumn = new TableColumn(table, SWT.NONE);
124.                                tableColumn.setWidth(100);
125.                                tableColumn.setText(rsmd.getColumnName(i));
126.                        }
127. 
128.                        TableItem tableItem = null;
129.                        SimpleDateFormat sdf = new SimpleDateFormat("yyyy/MM/dd");
130.                        int countRow = 0;
131.                        while( rs.next() && countRow < maxRows ) {
132. 
133.                                countRow++;
134. 
135.                                String[] columnData = new String[columnCount];
136. 
137.                                for( int i = 1; i <= columnCount; i++) {
138. 
139.                                        if ( rsmd.getColumnTypeName(i).equals("DATETIME") ) {
140.                                                columnData[i-1] = sdf.format(rs.getDate(i));
141.                                        }
142.                                        else {
143.                                                columnData[i-1] = rs.getString(i);
144.                                        }
145. 
146.                                }
147.                                tableItem = new TableItem(table, SWT.NONE);
148.                                tableItem.setText(columnData);
149.                        }
150. 
151.                        rs.close();
152.                        stmt.close();
153.                        conn.close();
154. 
155.                } catch (SQLException ex) {
156.                        // handle any errors
157.                        System.out.println("SQLException: " + ex.getMessage());
158.                        System.out.println("SQLState: " + ex.getSQLState());
159.                        System.out.println("VendorError: " + ex.getErrorCode());
160.                }
161. 
162.        }
163.}

pom.xml
01.<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">
02.  <modelVersion>4.0.0</modelVersion>
03.  <groupId>MySQL_01</groupId>
04.  <artifactId>MySQL_01</artifactId>
05.  <version>0.0.1-SNAPSHOT</version>
06.  <build>
07.    <sourceDirectory>src</sourceDirectory>
08.    <plugins>
09.      <plugin>
10.        <artifactId>maven-compiler-plugin</artifactId>
11.        <version>3.7.0</version>
12.        <configuration>
13.          <source>1.8</source>
14.          <target>1.8</target>
15.        </configuration>
16.      </plugin>
17.    </plugins>
18.  </build>
19.  <dependencies>
20.    <dependency>
21.      <groupId>mysql</groupId>
22.      <artifactId>mysql-connector-java</artifactId>
23.      <version>5.1.46</version>
24.    </dependency>
25.  </dependencies>
26. 
27.</project>

関連する記事

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