SQLの窓

2020年10月13日


HTML Application : JavaScript で新しい Excel の Book を作成する

JavaScript から Excel にアクセスする場合、『Quit メソッドを呼び出した後、Excel がシャットダウンしない』というバグがあるのでその対応を組み込んでいます



実行後に作成された Excel Book
<!DOCTYPE html>
<html>
<head>
<meta http-equiv="x-ua-compatible" content="ie=edge">
<meta charset="utf-8">
<meta content="width=device-width initial-scale=1.0 minimum-scale=1.0 maximum-scale=1.0 user-scalable=no" name="viewport">

<title>新しい Excel の Book を作成する</title>
<script src="https://ajax.googleapis.com/ajax/libs/jquery/3.5.1/jquery.min.js"></script>
<link rel="stylesheet" href="https://cdnjs.cloudflare.com/ajax/libs/twitter-bootstrap/4.5.2/css/bootstrap.min.css" integrity="sha512-MoRNloxbStBcD8z3M/2BmnT+rg4IsMxPkXaGh2zD6LGNNFE80W3onsAhRcMAMrSoyWL9xD7Ert0men7vR8LUZg==" crossorigin="anonymous" />

<style>
/* ****************************
 上下エリア
 フィットコントロール用
******************************/
html,body {
	height: 100%;
}
/* ****************************
 それぞれのエリアの特性
******************************/
/* 基本枠 */
body {
	margin: 0;
}
/* 上固定部分 */
#head {
	padding: 16px;
	display: block;
	margin: auto;
	width: 100%;							/* 幅 */
	height: 70px;							/* 高さ */
	background-color: #e0e0e0;
}
/* 下スクロール部分 */
#extend {
	padding: 4px 16px;
	display: block;
	margin: auto;
	width: calc( 100% - 3px );				/* 幅 */
	height: calc( 100% - 70px - 2px );		/* 高さ */
	border: solid 2px #c0c0c0;
	overflow: scroll;
}

</style>

<script>
// ****************************
// Excel.Application 用
// ****************************
var Excel = null;
var Book = null;
var Worksheet = null;
// 外部プログラムの実行用
var WshShell = new ActiveXObject("WScript.Shell");
var targetPath = WshShell.ExpandEnvironmentStrings("%TEMP%") + "\\新しいBook.xlsx";

// jQuery 用専用ロードイベント
$(function(){

	$("#filepath").text( targetPath );

	// ボタンのイベント
	$("#action").on("click", function(){

		// 実行確認
		if ( !confirm("新しいBook を作成してもよろしいですが?") ) {
			return;
		}
	
		// 複数の Excel 処理を対話で続ける時の為に Excel が null の時のみ作成する方法
		// ※ 今回は必ず実行後終了させるのでこの if 文は必要ありません
		if ( Excel == null ) {
			// ****************************
			// 基本オブジェクトを作成
			// ****************************
			Excel = new ActiveXObject("Excel.Application");
		}

		// ****************************
		// 表示( テストの時は表示 )
		// 完成した場合は false にしますが、
		// なんらかのエラーが起きた場合はタスクマネージャから Excel
		// を終了させる必要があります
		// ****************************
		Excel.Visible = true;

		// ****************************
		// 警告を出さないようにする
		// 使用すると上書きの警告が
		// 出なくなります
		// ****************************
		Excel.DisplayAlerts = false;

		// ****************************
		// ブック追加
		// ****************************
		Excel.Workbooks.Add();

		// ****************************
		// 追加したブックを取得
		// ※ 新規なのて 1 番目
		// ****************************
		Book = Excel.Workbooks( Excel.Workbooks.Count );

		// ****************************
		// 先頭シートを選択する
		// 少なくとも最初に一つシートが存在します
		// ****************************
		Worksheet = Book.Worksheets( 1 );

		// ****************************
		// シート名設定
		// ( アクティブなので直接 )
		// ****************************
		Worksheet.Name = "新しい情報";

		// ****************************
		// Add では 第二引数に指定した
		// オブジェクトのシートの直後に、
		// 新しいシートを追加します。
		// ****************************
		Book.Worksheets.Add(null,Worksheet);

		// ****************************
		// シート名設定
		// ( 2番目のシート )
		// ****************************
		Book.Worksheets(2).Name = "予備情報";

		// ****************************
		// 新しい情報 シートを選択
		// ****************************
		Book.Worksheets("新しい情報").Select();

		// ****************************
		// コード列を文字列に設定
		// ****************************
		Worksheet.Columns("A:A").Select();
		Excel.Selection.NumberFormatLocal = "@";
		Worksheet.Columns("D:D").Select();
		Excel.Selection.NumberFormatLocal = "@";
		Worksheet.Columns("J:J").Select();
		Excel.Selection.NumberFormatLocal = "@";

		// ****************************
		// テーブル情報をセルへセット
		// ****************************
		// タイトル部分の参照
		$("#tbl th").each(function(idx){
			Worksheet.Cells(1, idx+1) = $(this).text();
		});

		// 行一覧の参照
		$("#tbl tr").each(function(row){
			$(this).find("td").each(function(idx){
				Worksheet.Cells(row, idx+1) = $(this).text();
			});
		});

		// ****************************
		// セルをデータに合わせて
		// 整理して左上を選択
		// ****************************
		Worksheet.Columns("A:K").Select();
		Worksheet.Columns("A:K").EntireColumn.AutoFit();
		Worksheet.Range("A1").Select();

		// ****************************
		// 保存
		// 拡張子を .xls で保存するには
		// Call ExcelBook.SaveAs( FilePath, 56 ) とします
		// ****************************
		var filePath = $("#filepath").text();

		try {
			Book.SaveAs( filePath );
			Book.Close();
		}
		catch (e) {
			alert("Book.SaveAs でエラーが発生しました");

			console.dir(e);
			ExcelQuit();
			return;
		}

		// Excel の完全終了
		ExcelQuit();

		// ****************************
		// 終了確認
		// ****************************
		alert("処理が終了しました \n\n 保存したブックを開きます");

		// ****************************
		// Windows からの Excel 起動
		// ****************************
		WshShell.Run( "RunDLL32.EXE shell32.dll,ShellExec_RunDLL " + filePath );

	});

});

// ****************************
// JavaScript による
// Excel の完全終了処理
// ****************************
var idTmr = "";
function ExcelQuit() {
	Excel.Quit();
	Excel = null;
	idTmr = window.setTimeout("Cleanup();",1);
}
function Cleanup() {
	window.clearInterval(idTmr);
 	CollectGarbage();
}
</script>
</head>
<body>
	<div id="head">
		<input id="action" type="button" value="ブックの作成" class="btn btn-primary"> <span class="ml-5" id="filepath">c:\temp\新しいBook.xlsx</span>
	</div>

	<div id="extend">
		<table class="table table-striped">
		<tbody id="tbl">
			<tr><th>社員コード</th><th>氏名</th><th>フリガナ</th><th>所属</th><th>性別</th><th>作成日</th><th>更新日</th><th>給与</th><th>手当</th><th>管理者</th><th>生年月日</th></tr>
			
			<tr><td>0001</td><td>山田 太郎</td><td>ウラオカ トモヤ</td><td>0003</td><td>0</td><td>2005-09-12</td><td>2005-11-28</td><td>400000</td><td>9000</td><td>0001</td><td>2012/03/21</td></tr>
			<tr><td>0002</td><td>山村 洋代</td><td>ヤマムラ ヒロヨ</td><td>0003</td><td>1</td><td>2005-06-17</td><td>2005-09-18</td><td>300000</td><td></td><td>0001</td><td>2001/01/02</td></tr>
			<tr><td>0003</td><td>多岡 冬行</td><td>タオカ フユユキ</td><td>0002</td><td>0</td><td>2005-08-14</td><td>2005-11-14</td><td>250000</td><td></td><td>0001</td><td>2001/01/01</td></tr>
			<tr><td>0004</td><td>高田 冬美</td><td>タカタ フユミ</td><td>0003</td><td>1</td><td>2005-06-13</td><td>2005-10-05</td><td>250000</td><td></td><td>0001</td><td>2001/01/01</td></tr>
			<tr><td>0005</td><td>内高 友之</td><td>ウチタカ トモユキ</td><td>0003</td><td>0</td><td>2005-09-12</td><td>2005-11-10</td><td>150000</td><td></td><td></td><td>2001/01/01</td></tr>

		</tbody>
		</table>

	</div>

</body>
</html>


▼ 以下の設定を IE11 で行うと、拡張子を .html に変更して IE11 でも実行できます






このページの PDF



posted by lightbox at 2020-10-13 09:54 | HTA ( HTMLアプリケーション ) | このブログの読者になる | 更新情報をチェックする

2020年10月11日


Java + Swing : JTable に CSV フォーマットのテキストファイルを読み込む

動作確認は、以下の環境で行っています
JDK11
✅ Visual Studio Code + Java Extension Pack
テキストファイルの入力は行毎に読み込む方法で、オーソドックスな以下のクラスを使います。 ✅ FileInputStream => InputStreamReader => BufferedReader キャラクタセットの設定は InputStreamReader で行い、読み込みは BufferedReader の readLine を使用したループ処理です
while ( null != (line_buffer = br.readLine() ) ) {
	// ループ処理
}
import java.awt.BorderLayout;
import java.awt.EventQueue;
import java.awt.event.ActionEvent;
import java.awt.event.ActionListener;
import java.io.BufferedReader;
import java.io.FileInputStream;
import java.io.InputStreamReader;

import javax.swing.JButton;
import javax.swing.JFrame;
import javax.swing.JPanel;
import javax.swing.JScrollPane;
import javax.swing.JTable;
import javax.swing.border.EmptyBorder;
import javax.swing.table.DefaultTableModel;
import javax.swing.table.TableColumn;

public class Main extends JFrame {

	private JPanel contentPane;
	private JTable table;
	private JPanel panel;

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

	// コンストラクタ
	public Main() {

		setDefaultCloseOperation(JFrame.EXIT_ON_CLOSE);
		setBounds(100, 100, 1000, 700);
		contentPane = new JPanel();
		contentPane.setBorder(new EmptyBorder(5, 5, 5, 5));
		setContentPane(contentPane);

		// ボタン
		JButton btnNewButton = new JButton("読み込み");
		btnNewButton.setBounds(10, 10, 91, 21);
		btnNewButton.addActionListener(new ActionListener() {
			public void actionPerformed(ActionEvent e) {
				
				loadCsv();
				
			}
		});
		
		contentPane.setLayout(null);
		contentPane.add(btnNewButton);
		
		panel = new JPanel();
		panel.setBounds(12, 52, 960, 600);
		panel.setLayout(new BorderLayout(0, 0));
		contentPane.add(panel);
		
		table = new JTable() {

			@Override
			public boolean isCellEditable(int row, int column) {
				return false;
			}
			
		};

		JScrollPane scrollPane = new JScrollPane(table);
		panel.add(scrollPane);
		
		scrollPane.setVerticalScrollBarPolicy(
				JScrollPane.VERTICAL_SCROLLBAR_AS_NEEDED);
		scrollPane.setHorizontalScrollBarPolicy(
				JScrollPane.HORIZONTAL_SCROLLBAR_AS_NEEDED);

	}
	
	// ********************
	// 初期化
	// ********************
	private void reset() {

		DefaultTableModel dtm = (DefaultTableModel) table.getModel();
		dtm.setRowCount(0);
		
		int cols = table.getColumnCount();

		for( int i = cols-1; i >= 0; i-- ) {
			table.removeColumn((table.getColumnModel()).getColumn(i));
		}
		
		// データモデルも初期化
		dtm.setColumnCount(0);

	}
	// ********************
	// 行を全て削除
	// ********************
	private void clear(){
		DefaultTableModel dtm = (DefaultTableModel) table.getModel();
		dtm.setRowCount(0);
	}
	
	// ********************
	// CSV
	// ********************
	private void loadCsv(){
		
		reset();

		try {

			FileInputStream fis = new FileInputStream("c:\\app\\java20\\sample-10-12\\社員マスタ.csv");
			InputStreamReader isr = new InputStreamReader(fis, "MS932");
			BufferedReader br = new BufferedReader(isr);

			String line_buffer;
			String[] adata;
			int line_count = -1;
			while ( null != (line_buffer = br.readLine() ) ) {

				// カンマで分解
				adata = line_buffer.split(",");

				// 1行目はタイトル
				if ( line_count == -1 ) {
					int count = adata.length;
					// 先に全ての列を登録する必要があります
					for( int i = 0; i < count; i++) {
						String id = String.format("col%d", i);
						addColumn( table,  id );
					}
					// タイトル文字列の変更を行っています。
					// 変更しない場合は、タイトルは列を登録時の第二引数になります
					int i = 0;
					for( String value:  adata ) {
						String id = String.format("col%d", i++);
						setColumnTitle( table, id, value );
					}
				}
				// 2行目以降がデータ
				else {
					addRow(table);
					int i = 0;
					for( String value:  adata ) {
						setColumn( table, line_count, i++, value );
					}
				}

				line_count++;

			}
			
			br.close();
			isr.close();
			fis.close();
		}
		catch (Exception e) {
			e.printStackTrace();
		}
		
	}
	
	// ****************************
	// 列の追加	
	// ****************************
	private void addColumn(JTable table, String name) {
		DefaultTableModel dtm = (DefaultTableModel) table.getModel();
		dtm.addColumn(name);
	}
	// ****************************
	// 列のタイトル文字列変更
	// ****************************
	private void setColumnTitle(JTable table, String name,String title) {
		TableColumn tc1 = table.getColumn(name);
		 tc1.setHeaderValue(title);
		 tc1.setIdentifier(name);
	}
	// ****************************
	// 空の行追加
	// ****************************
	private void addRow(JTable table) {
		DefaultTableModel dtm = (DefaultTableModel) table.getModel();
		Object[] obj  = null;
		dtm.addRow(obj);
	}
	// ****************************
	// 指定カラムへデータをセット
	// ****************************
	private void setColumn(JTable table,int row,int col, String data) {
		table.setValueAt( data, row,  col  );
	}
	
}




posted by lightbox at 2020-10-11 21:21 | java : Swing | このブログの読者になる | 更新情報をチェックする

Python : shift_jis の3列の csv フォーマットのデータを ttk.Treeview に表示する



Python : ttk.Treeview で表形式を使用して環境変数の一覧表示 で作成した Treeview を利用しました

sample_textfile.py
# shift_jis の3列の csv フォーマットのデータを Treeview に表示する
#
from buill_grid import *

with open('cp932.txt', encoding='cp932') as fp:
	for line_buffer in fp:
		# 行末の改行を削除する
		line_buffer = line_buffer.rstrip("\n")
		print(line_buffer)
		# カンマで分割
		csv = line_buffer.split(",")
		print(csv)
		# Treeview にセット
		grid.insert("","end",values=(f"{csv[0]}",f"{csv[1]}", f"{csv[2]}"))

# ウインドウ開始
form.mainloop()

buill_grid.py
import tkinter as tk
import tkinter.ttk as ttk

# メインフォーム
form = tk.Tk()
form.title("タイトル")
form.geometry("800x600")

# ツリービュー(表)
grid = ttk.Treeview(form, show="headings")

# 列ID
grid["columns"] = ("A","B","C")

# 列幅
grid.column("A", width=150)
grid.column("B", width=150)
grid.column("C", width=150)

# タイトル
grid.heading("A", text="A")
grid.heading("B", text="B")
grid.heading("C", text="C")

# 位置指定して作成
grid.place(x=20, y=40, height=500)

# スクロールバーを同期させて form に配置
vsb = ttk.Scrollbar(form, orient="vertical", command=grid.yview)
vsb.place(x=20+450+3, y=40+3, height=500)
grid.configure(yscrollcommand=vsb.set)





posted by lightbox at 2020-10-11 19:41 | Python | このブログの読者になる | 更新情報をチェックする

Python : ttk.Treeview で表形式を使用して環境変数の一覧表示



※ 列の ID は、視認性を上げる為に日本語の名称を使用しています。

import os
import tkinter as tk
import tkinter.ttk as ttk

# メインフォーム
form = tk.Tk()
form.title("タイトル")
form.geometry("800x600")

# ツリービュー(表)
grid = ttk.Treeview(form, show="headings")

# 列ID
grid["columns"] = ("番号","変数","値")

# 列幅
grid.column("番号", width=30)
grid.column("変数", width=150)
grid.column("値", width=500)

# タイトル
grid.heading("番号", text="")
grid.heading("変数", text="変数")
grid.heading("値", text="値")

# データ
i = 0
for k, v in os.environ.items():
	i = i + 1
	grid.insert("","end",values=(i,f"{k}", f"{v}"))

# 位置指定して作成
grid.place(x=20, y=40, height=500)

# スクロールバーを同期させて form に配置
vsb = ttk.Scrollbar(form, orient="vertical", command=grid.yview)
vsb.place(x=20+680+3, y=40+3, height=500)
grid.configure(yscrollcommand=vsb.set)


form.mainloop()

スクロールバー部分は、Stack OverFlow の『Python Treeview scrollbar』を参考にしています



posted by lightbox at 2020-10-11 00:11 | Python | このブログの読者になる | 更新情報をチェックする

2020年09月21日


nuget.exe CLI を使用してパッケージをダウンロードし、C# のソースコードで利用して PowerShell でビルドする

 ps.bat ( PowerShell をそのまま使えない場合は以下のバッチファイルを作成して使用します )
@powershell -NoProfile -ExecutionPolicy Unrestricted "./%1.ps1"
nuget.exe - recommended latest のダウンロードページ nuget.exe CLI を使用してパッケージを管理する( Microsoft のドキュメント )
nuget.exe を最新にするには
nuget update -Self

ここで使用するパッケージの最新バージョンの確認は こちらから 行って以下のコマンドライン
nuget install Newtonsoft.Json -Version バージョン
json_sample_01.cs
using System;
using System.IO;
using System.Text;
using System.Net;
using System.Web;
using System.Windows.Forms;
using Newtonsoft.Json;

public class Program
{
	public static void Main()
	{
		ServicePointManager.SecurityProtocol = SecurityProtocolType.Tls12;	

		string url = "https://lightbox.sakura.ne.jp/demo/json/syain_json.php";
		
		string json = "";

		using( WebClient wc = new WebClient() ) {
			wc.Encoding = Encoding.UTF8;
			json = wc.DownloadString( url );
		}

		Syain[] syain = JsonConvert.DeserializeObject<Syain[]>(json);

		foreach (Syain data in syain) {
			Console.WriteLine( data.社員コード );
			Console.WriteLine( data.氏名 );
			Console.WriteLine( data.フリガナ );
		}

		MessageBox.Show("処理が終了しました");

	}

	private class Syain
	{
		public string 社員コード  { get; set; }
		public string 氏名  { get; set; }
		public string フリガナ  { get; set; }
	}

}


build.ps1

Newtonsoft.Json.dll は、ソースコードと同じ場所に置きます
Add-Type -path "json_sample_01.cs" `
	-ReferencedAssemblies "Newtonsoft.Json.dll", System.Web, System.Windows.Forms `
	-OutputAssembly json_sample_01.exe `
	-OutputType ConsoleApplication

Read-Host "何かキーを押してください"


run.ps1

Newtonsoft.Json.dll は、ソースコードと同じ場所に置きます
Add-Type -path "Newtonsoft.Json.dll"
Add-Type -path "json_sample_01.cs" `
	-ReferencedAssemblies "Newtonsoft.Json.dll", System.Web, System.Windows.Forms

[Program]::Main()

Read-Host "何かキーを押してください"




posted by lightbox at 2020-09-21 18:32 | PowerShell + C# | このブログの読者になる | 更新情報をチェックする

2020年09月01日


XAMPP + Python( 3.8 ) で WEBアプリの基礎部分構築 : その ( 1 )

最初は、基本的なデータ型の表示テストです。



XAMPP で Python を実行できるようにするには、httpd.conf の 『AddHandler cgi-script .cgi .pl .asp』 に .py を追加します


( Apache 環境では、.py に対してソースコードの先頭の #!プログラム をcgi として実行します / PHP は別定義です )

Windows では、Python の先頭に Python の実行プログラムの場所を記述しなくても、Windows のレジストリに設定して動作できるようにする事ができるようです
( 💘 ScriptInterpreterSource Registry-Strict )

以下は、Windows 環境下で .py に対して実行される処理として設定される内容です
Python のダウンロードとインストールは こちら(Windows 環境のPython) がとても参考になります 上記リンク先のフル・インストーラ版で python-3.8.5-amd64.exe をインストールすると、拡張子の関連付けで .py に対して 『"C:\WINDOWS\py.exe" "%L" %*』が登録されます Python.File は、ファイルのタイプとして登録される詳細ですが、このエントリが拡張子と関連付けられます。確認は、コマンドプロンプトで 『assoc .py』で確認できますが、レジストリでも確認できます 以下のプロパティはインストールされた py.exe と python.exe です 以下は、仮想ディレクトリの作成です
<IfModule alias_module>

    Alias /py "/app/py20"
    <Directory "/app/py20">
        Options Indexes FollowSymLinks Includes ExecCGI
        AllowOverride All
        Require all granted
    </Directory>

</IfModule>
sample_01.py
#!C:\python\python.exe

import cgi
import cgitb
cgitb.enable()

import sys
import io
import os
import urllib.parse
from xml.sax.saxutils import *

sys.stdout = io.TextIOWrapper(sys.stdout.buffer, encoding='utf-8')

print("Content-Type: text/html; charset=utf-8")
print( "Expires: Thu, 19 Nov 1981 08:52:00 GMT" )
print( "Cache-Control: no-store, no-cache, must-revalidate, post-check=0, pre-check=0" )
print( "Pragma: no-cache" )
print()

data1 = "こんにちは"
data2 = [1,2,3,4]
data3 = (1,2,3,4,"")
data4 = {"A":1, "B":2, "C":3, "D":4 }

type1 = str(type(data1))
type2 = str(type(data2))
type3 = str(type(data3))
type4 = str(type(data4))

print( data1 + "<br>" )
print( escape(type1) + "<br>" )

print( str(data2) + "<br>" )
print( escape(type2) + "<br>" )

print( str(data3) + "<br>" )
print( escape(type3) + "<br>" )

print( str(data4) + "<br>" )
print( escape(type4) + "<br>" )



関連する記事

XAMPP + Python( 3.8 ) で WEBアプリの基礎部分構築 : その ( 1 )

XAMPP + Python( 3.8 ) でWEBアプリの基礎部分構築 : その ( 2 ) : QUERY_STRING と 画面定義

XAMPP + Python( 3.8 ) で WEBアプリの基礎部分構築 : その ( 3 ) : cgi.FieldStorage() から ディクショナリ

XAMPP + Python( 3.8 ) で WEBアプリの基礎部分構築 : その ( 4 ) : リダイレクトと関数とログ出力



posted by lightbox at 2020-09-01 11:15 | Python | このブログの読者になる | 更新情報をチェックする

2020年08月31日


VBScript : ADO : ODBC接続 : SQLExpress(SQLServer) 接続と通常処理( 更新は SQL で行う )



ドライバは、古い {SQL Server} ドライバを使用していますが、VBS では、{SQL Native Client} を使っても同じだと思います。

SQLExpress(SQLServer) の 32ビット クライアントの設定です

MSSQLServer のレジストリ位置を開く VBScript のダウンロード

※ コメント部分ですが、このサンプルで SQL の更新を接続オブシェクトのメソッドで SQL 文字列を使って実行しています。

フィールドオブジェクトにセットして更新する方法もありますが、他の言語間での移植が困難になるので、このほうが良い環境はたくさんあると思います

関連する記事

SQLExpress 2005 の接続設定
VBScript : ADO : フィールドオブジェクトを使用した同一フォーマットのテーブル間のデータコピー
VBScript : ADO : 純正接続 : SQLExpress(SQLServer) 接続と通常処理

SQLExpress にインポートするデータ(MDB)


' ***********************************************************
' SQLExpress / ODBC / {SQL Server}
' ADO : 文字列更新
' FileSystemObject : CSV出力
' ***********************************************************
strDriver = "{SQL Server}"
strTarget = "reiwa"		' 別名
strDB = "lightbox"
strUser = "sa"
strPass = "passwordpassword"

' ***********************************************************
' ADO + FileSystemObject
' ***********************************************************
Set Cn = CreateObject( "ADODB.Connection" )
Set Rs = CreateObject( "ADODB.Recordset" )
Set Fso = CreateObject( "Scripting.FileSystemObject" )

' **********************************************************
' 接続文字列
' **********************************************************
ConnectionString = _
	"Provider=MSDASQL;" & _
	"Driver=" & strDriver & ";" & _
	"SERVER=" & strTarget & ";" & _
	"DATABASE=" & strDB & ";" & _
	"UID=" & strUser & ";" & _
	"PWD=" & strPass & ";"

' **********************************************************
' 接続
' クライアントカーソル(3)を使う事が推奨されます
' **********************************************************
Cn.CursorLocation = 3
on error resume next
Cn.Open ConnectionString
if Err.Number <> 0 then
	WScript.Echo Err.Description
	Wscript.Quit
end if
on error goto 0

Query = "select * from [社員マスタ]"

' **********************************************************
' レコードセット
' オブジェクト更新時はレコード単位の共有的ロック(3)を
' 使用します( デフォルトでは更新できません )
' ※ デフォルトでも SQLによる更新は可能です
' **********************************************************
'Rs.LockType = 3
on error resume next
Rs.Open Query, Cn
if Err.Number <> 0 then
	Cn.Close
	Wscript.Echo Err.Description
	Wscript.Quit
end if
on error goto 0

' **********************************************************
' 出力ファイルオープン
' **********************************************************
Set Csv = Fso.CreateTextFile( "社員マスタ.csv", True )

' **********************************************************
' タイトル出力
' **********************************************************
Buffer = ""
For i = 0 to Rs.Fields.Count - 1
	if Buffer <> "" then
		Buffer = Buffer & ","
	end if
	Buffer = Buffer & Rs.Fields(i).Name
Next
Csv.WriteLine Buffer

' **********************************************************
' データ出力
' **********************************************************
' UpdateCnt = 0
Do While not Rs.EOF
	Buffer = ""
	For i = 0 to Rs.Fields.Count - 1
		if Buffer <> "" then
			Buffer = Buffer & ","
		end if
		Buffer = Buffer & Rs.Fields(i).Value
	Next

	' 更新
'	strDay = (UpdateCnt mod 10) + 1
'	Query = "update [社員マスタ] set [生年月日] = '2005/01/0" & strDay & "'"
'	Query = Query & " where 社員コード = '" 
'	Query = Query & Rs.Fields("社員コード").Value
'	Query = Query & "'"
	Cn.Execute( Query )

	Csv.WriteLine Buffer
	Rs.MoveNext
'	UpdateCnt = UpdateCnt + 1
Loop

' **********************************************************
' ファイルクローズ
' **********************************************************
Csv.Close
' **********************************************************
' レコードセットクローズ
' **********************************************************
Rs.Close
' **********************************************************
' 接続解除
' **********************************************************
Cn.Close


hanbaic.mdb よりインポートする為の バッチファイル
C:\Windows\SysWOW64\cscript.exe import.vbs
Windows10 64ビットで、Office が 32ビットの場合を想定しています

hanbaic.mdb よりインポートする為の VBScript
' ***********************************************************
' hanbaic.mdb からインポート
' ***********************************************************
strMdbPath = "C:\Users\lightbox\Downloads\hanbaic_mdb\hanbaic.mdb"
strConnect = "Provider=Microsoft.ACE.OLEDB.12.0;Data Source=" & strMdbPath & ";"

' ***********************************************************
' ADO
' ***********************************************************
Set Cn = CreateObject( "ADODB.Connection" )

' **********************************************************
' MDB 用接続文字列
' **********************************************************
ConnectionString = "Provider=Microsoft.ACE.OLEDB.12.0;Data Source=" & strMdbPath & ";"

' **********************************************************
' 接続
' **********************************************************
on error resume next
Cn.Open ConnectionString
if Err.Number <> 0 then
	WScript.Echo Err.Description
	Wscript.Quit
end if
on error goto 0

' **********************************************************
' 実行
' **********************************************************
RefString = "[ODBC;Driver={SQL Server};Server=reiwa;Database=lightbox;Uid=sa;Pwd=passwordpassword]"
Query = "select * into " & RefString & ".[社員マスタ] from [社員マスタ]"

on error resume next
Cn.Execute Query
if Err.Number <> 0 then
	WScript.Echo Err.Description
	Wscript.Quit
end if
on error goto 0

' **********************************************************
' 接続解除
' **********************************************************
Cn.Close




posted by lightbox at 2020-08-31 09:06 | SQLExpress | このブログの読者になる | 更新情報をチェックする

2020年08月30日


タスクマネージャーで、実行中のアプリケーションが 32 ビットか 64 ビットかを確認する

詳細タブを選択
タイトル部分を右クリックして、列の選択をクリック
表示されたダイアログで、『プラットフォーム』にチェック

※ IE11 の場合は、32ビットの行があれば 32ビット






posted by lightbox at 2020-08-30 18:42 | Windows10 | このブログの読者になる | 更新情報をチェックする

PowerShell を使用して、C# のコンソールアプリ用のソースコードから exe を作成する( WebClient で wget.exe ) / ビルドせずに PowerShell で実行

▼ ps.bat ( PowerShell をそのまま使えない場合は以下のバッチファイルを作成して使用します )
@powershell -NoProfile -ExecutionPolicy Unrestricted "./%1.ps1"
▼ build.ps1
Add-Type -path "wget.cs" `
	-ReferencedAssemblies System.Web, System.Windows.Forms `
	-OutputAssembly my_wget.exe `
	-OutputType ConsoleApplication

Read-Host "何かキーを押してください"


wget.cs は、wget.ps1 と同じフォルダにあります
 ` で継続行指定です。
System.Web, System.Windows.Forms という感じで複数の指定を行っています

▼ wget.cs

第一引数に渡した URL をダウンロードします。
Environment.GetCommandLineArgs() の結果には、自分自身が含まれています。
よって、param[1] と args[0] が同じ内容になります。( 後述の PowerShell から実行した場合は、param には PowerShell への引数がセットされます )
Visual Studio で追加参照が必要なクラスが -ReferencedAssemblies の対象です
using System;
using System.IO;
using System.Net;
using System.Web;
using System.Windows.Forms;

public class Program
{
	public static void Main(string[] args)
	{
		ServicePointManager.SecurityProtocol = SecurityProtocolType.Tls12;	

		string[] param = Environment.GetCommandLineArgs();
		if (param.Length > 1)
		{
			Console.WriteLine( string.Format("第一引数 : {0}", param[1]) );
			Console.WriteLine(string.Format("第一引数 : {0}", args[0]));
		}
		else
		{
			MessageBox.Show("ダウンロードする URL を引数に指定して下さい");
			Environment.Exit(0);
		}

		string localFileName = Path.GetFileName(param[1]);
		Console.WriteLine(string.Format("ファイル名 : {0}", localFileName));

		using( WebClient wc = new WebClient() ) {
			wc.DownloadFile( param[1], localFileName );
		}

		// *******************************************
		// -ReferencedAssemblies の複数テスト用
		// *******************************************
		string percent_encoding = HttpUtility.UrlEncode(param[1]);
		Console.WriteLine( percent_encoding );

		MessageBox.Show("処理が終了しました");

	}
}


MessageBox.Show
HttpUtility.UrlEncode

▼ 実行用バッチファイルのサンプル
my_wget.exe https://winofsql.jp/image/planet.jpg
▼ 実行結果の表示
C:\user\ps\cs>my_wget.exe http://winofsql.jp/image/planet.jpg
第一引数 : http://winofsql.jp/image/planet.jpg
第一引数 : http://winofsql.jp/image/planet.jpg
ファイル名 : planet.jpg
http%3a%2f%2fwinofsql.jp%2fimage%2fplanet.jpg
この後、メッセージボックスが表示されます PowerShell として exe なしで実行する場合 ▼ run.ps1
Param($url)
Write-Host $url

Add-Type -path "wget.cs" `
	-ReferencedAssemblies System.Web, System.Windows.Forms

[Program]::Main($url)

Read-Host "何かキーを押してください"

実行
powershell -NoProfile -ExecutionPolicy Unrestricted run.ps https://winofsql.jp/image/planet.jpg

スクリプトセットのダウンロード




関連するドキュメント


Read-Host コマンドレットの使用
Add-Type




posted by lightbox at 2020-08-30 14:33 | PowerShell + C# | このブログの読者になる | 更新情報をチェックする

2020年08月23日


エクスプローラを右クリックしてそのフォルダで「コマンドプロント」を開くメニューを追加する .reg ファイル



ZIP ダウンロード



エクスプローラを右クリックしてコマンドプロンプトを開きたい場合は、以下のレジストリをインポートします

Windows Registry Editor Version 5.00
 
[HKEY_CLASSES_ROOT\Directory\shell\usercmd]
@="コマンドプロンプトをここで開く(&P)"
 
[HKEY_CLASSES_ROOT\Directory\shell\usercmd\command]
@="cmd.exe /s /k pushd \"%V\""


削除用

Windows Registry Editor Version 5.00
 
[-HKEY_CLASSES_ROOT\Directory\shell\usercmd]
 




このページの PDF



posted by lightbox at 2020-08-23 10:59 | コマンドプロンプト | このブログの読者になる | 更新情報をチェックする

2020年08月20日


XAMPP + Python( 3.8 ) で WEBアプリの基礎部分構築 : その ( 4 ) : リダイレクトと関数とログ出力

def を使用して ファイルにログを書き込む処理を定義し、REQUEST_METHOD で判断して POST 時にリダイレクトを行います



XAMPP で Python を実行できるようにするには、httpd.conf の 『AddHandler cgi-script .cgi .pl .asp』 に .py を追加します



Windows では、Python の先頭に Python の実行プログラムの場所を記述しなくても、Windows のレジストリに設定して動作できるようにする事ができるようです
( 💘 ScriptInterpreterSource Registry-Strict )

Python のダウンロードとインストールは こちら(Windows 環境のPython) がとても参考になります

sample_04.py

REQUEST_METHOD を取得して、POST 時に HTTP ヘッダにリダイレクト処理を入れたり、ログ出力を実行するようにしています
if method == "POST":
	print( "Location: sample_04.py?field3=%E5%B1%B1%E7%94%B0%20%E5%A4%AA%E9%83%8E" )

#!C:\python\python.exe

import cgi
import cgitb
cgitb.enable()

import sys
import io
import os
import urllib.parse
from xml.sax.saxutils import *

# **************************************
# ログ出力
# **************************************
def log( message ):
	with open('debug.log', 'a') as f:
		print(message,end='\n',file=f)

sys.stdout = io.TextIOWrapper(sys.stdout.buffer, encoding='utf-8')

method = os.environ["REQUEST_METHOD"]

print("Content-Type: text/html; charset=utf-8")
print( "Expires: Thu, 19 Nov 1981 08:52:00 GMT" )
print( "Cache-Control: no-store, no-cache, must-revalidate, post-check=0, pre-check=0" )
print( "Pragma: no-cache" )
if method == "POST":
	print( "Location: sample_04.py?field3=%E5%B1%B1%E7%94%B0%20%E5%A4%AA%E9%83%8E" )
print()

form = cgi.FieldStorage()

# form 用データの内容です
result = str(form) + "<br>"
if method == "POST":
	log( form )

form_data = {}
fields = [ "field1", "field2", "field3", "field4", "send" ]
for field_name in fields:
	if field_name not in form:
		form_data[field_name] = ""
	else:
		form_data[field_name] = form.getvalue(field_name)

# 以降で使用可能なディクショナリの内容です
result += str(form_data) + "<br>"
if method == "POST":
	log( form_data )

view = f"""<!DOCTYPE html>
<html>
<head>
<meta content="width=device-width, initial-scale=1.0, minimum-scale=1.0, maximum-scale=1.0, user-scalable=no" name="viewport">
<meta charset="UTF-8">
<link rel="stylesheet" href="https://cdnjs.cloudflare.com/ajax/libs/twitter-bootstrap/4.5.0/css/bootstrap.css">

<style>
#main {{
	padding: 30px;
	font-size: 24px;
}}

form {{
	margin-bottom: 20px;
}}

.inline {{
	display: inline-block;
}}
.ttl {{
	width: 100px;
}}
</style>
</head>
<body>
<div id="main">

	<form method="post">
		<div>
			<div class="inline ttl">氏名</div>
			<div class="inline"><input type="text" name="field3" value="{form_data["field3"]}"></div>
		</div>

		<div>
			<div class="inline ttl">フリガナ</div>
			<div class="inline"><input type="text" name="field4" value="{form_data["field4"]}"></div>
			<div class="inline ml-2"><input type="submit" name="send" value="送信"></div>
		</div>
	</form>

	{result}

</div>
</body>
</html>"""

print(view)


関連する記事

XAMPP + Python( 3.8 ) で WEBアプリの基礎部分構築 : その ( 1 )

XAMPP + Python( 3.8 ) でWEBアプリの基礎部分構築 : その ( 2 ) : QUERY_STRING と 画面定義

XAMPP + Python( 3.8 ) で WEBアプリの基礎部分構築 : その ( 3 ) : cgi.FieldStorage() から ディクショナリ

XAMPP + Python( 3.8 ) で WEBアプリの基礎部分構築 : その ( 4 ) : リダイレクトと関数とログ出力


posted by lightbox at 2020-08-20 16:54 | Python | このブログの読者になる | 更新情報をチェックする

2020年08月19日


XAMPP + Python( 3.8 ) で WEBアプリの基礎部分構築 : その ( 3 ) : cgi.FieldStorage() から ディクショナリ

Python の CGI の機能を使用して form の内容( GET と POST 混在 )を取得して使用します



XAMPP で Python を実行できるようにするには、httpd.conf の 『AddHandler cgi-script .cgi .pl .asp』 に .py を追加します



Windows では、Python の先頭に Python の実行プログラムの場所を記述しなくても、Windows のレジストリに設定して動作できるようにする事ができるようです
( 💘 ScriptInterpreterSource Registry-Strict )

Python のダウンロードとインストールは こちら(Windows 環境のPython) がとても参考になります

sample_03.py
form_data = {}
fields = [ "field1", "field2", "field3", "field4", "send" ]
for field_name in fields:
	if field_name not in form:
		form_data[field_name] = ""
	else:
		form_data[field_name] = form.getvalue(field_name)
cgi.FieldStorage() で取得された from をディクショナリである form_data に変換して使用します
#!C:\python\python.exe

import cgi
import cgitb
cgitb.enable()

import sys
import io
import os
import urllib.parse
from xml.sax.saxutils import *

sys.stdout = io.TextIOWrapper(sys.stdout.buffer, encoding='utf-8')

print("Content-Type: text/html; charset=utf-8")
print( "Expires: Thu, 19 Nov 1981 08:52:00 GMT" )
print( "Cache-Control: no-store, no-cache, must-revalidate, post-check=0, pre-check=0" )
print( "Pragma: no-cache" )
print()

print( "<div style='padding:30px;font-size:20px;word-break:break-all;'>" )

form = cgi.FieldStorage()

# form 用データの内容です
print( str(form) + "<br>")

form_data = {}
fields = [ "field1", "field2", "field3", "field4", "send" ]
for field_name in fields:
	if field_name not in form:
		form_data[field_name] = ""
	else:
		form_data[field_name] = form.getvalue(field_name)

# 以降で使用可能なディクショナリの内容です
print(str(form_data) + "<br>")

print( "</div>" )

view = f"""<!DOCTYPE html>
<html>
<head>
<meta content="width=device-width, initial-scale=1.0, minimum-scale=1.0, maximum-scale=1.0, user-scalable=no" name="viewport">
<meta charset="UTF-8">
<link rel="stylesheet" href="https://cdnjs.cloudflare.com/ajax/libs/twitter-bootstrap/4.5.0/css/bootstrap.css">

<style>
#main {{
	padding: 30px;
	font-size: 24px;
}}

form {{
	margin-bottom: 20px;
}}

.inline {{
	display: inline-block;
}}
.ttl {{
	width: 100px;
}}
</style>
</head>
<body>
<div id="main">
	<form method="get">
		<div>
			<div class="inline ttl">氏名</div>
			<div class="inline"><input type="text" name="field1" value="{form_data["field1"]}"></div>
		</div>

		<div>
			<div class="inline ttl">フリガナ</div>
			<div class="inline"><input type="text" name="field2" value="{form_data["field2"]}"></div>
			<div class="inline ml-2"><input type="submit" name="send" value="送信"></div>
		</div>
	</form>

	<form method="post">
		<div>
			<div class="inline ttl">氏名</div>
			<div class="inline"><input type="text" name="field3" value="{form_data["field3"]}"></div>
		</div>

		<div>
			<div class="inline ttl">フリガナ</div>
			<div class="inline"><input type="text" name="field4" value="{form_data["field4"]}"></div>
			<div class="inline ml-2"><input type="submit" name="send" value="送信"></div>
		</div>
	</form>

</div>
</body>
</html>"""

print(view)


関連する記事

XAMPP + Python( 3.8 ) で WEBアプリの基礎部分構築 : その ( 1 )

XAMPP + Python( 3.8 ) でWEBアプリの基礎部分構築 : その ( 2 ) : QUERY_STRING と 画面定義

XAMPP + Python( 3.8 ) で WEBアプリの基礎部分構築 : その ( 3 ) : cgi.FieldStorage() から ディクショナリ

XAMPP + Python( 3.8 ) で WEBアプリの基礎部分構築 : その ( 4 ) : リダイレクトと関数とログ出力



posted by lightbox at 2020-08-19 16:26 | Python | このブログの読者になる | 更新情報をチェックする
container 終わり



フリーフォントで簡単ロゴ作成
フリーフォントでボタン素材作成
フリーフォントで吹き出し画像作成
フリーフォントではんこ画像作成
ほぼ自由に利用できるフリーフォント
フリーフォントの書体見本とサンプル
画像を大きく見る為のウインドウを開くボタンの作成
CSS ドロップシャドウの参考デモ
イラストAC
ぱくたそ
写真素材 足成
フリーフォント一覧
utf8 文字ツール
右サイド 終わり
base 終わり