LoginSignup
31
25

More than 5 years have passed since last update.

ExcelからPHP動かしてみた

Last updated at Posted at 2015-06-05

ExcelからPHP動かしてみた

なんかExcelでVBA使っててふと、これ外部スクリプトで処理してデータ受け取れたらなと思い、どうやらコンソールを使えば行けそうな感じがしたのでやってみました。

とりあえず簡単に動かしたかったのでスクリプトはPHPを使用しましたがコンソールで動けば多分なんでもいけると思います。

手順としては
Excel → VBA → 標準入出力 → PHP → 標準入出力 → VBA → Excel
な感じです。

excel_php_test.xlsm
Sub テスト()

Dim path As String
Dim before As String

Dim WSH, Exec_cmd, Com As String
Dim Result As String
Dim head, foot() As String

'現在のパス
path = ThisWorkbook.path
'変換元値
before = Range("B3").Value

'コマンドプロンプトオブジェクト
Set WSH = CreateObject("WScript.Shell")
'コマンド生成
Com = "php " & path & "\excel_php_test.php"
'コマンド実行
Set Exec_cmd = WSH.Exec("%ComSpec% /c " & Com)
'標準入力
Exec_cmd.StdIn.WriteLine (before)
'終わるまで待つ
Do While Exec_cmd.Status = 0
        DoEvents
    Loop
    '結果を全部Resultに
    Result = Exec_cmd.StdOut.ReadAll
'頭区切り文字列で分ける
head = Split(Result, " header ")
'尻区切り文字列で分ける
foot = Split(head(1), " footer ")
'foot(0)に変換後の値が入る(はず)
Range("D3").Value = foot(0)

End Sub
excel_php_test.php
<?php

//標準入力
$str = trim(fgets(STDIN));
//$str = mb_convert_encoding($strIn, "UTF-8", "SJIS");

//標準出力用ヘッダー
$header = " header ";
$footer = " footer ";


//処理
$strCh = $str."食べたい";

//出力用にSJISに
//$strOut = mb_convert_encoding($strCh, 'SJIS', 'UTF-8');

//出力
//確認用
echo "変換前 -> ".$str." 変換後 -> ".$strCh."\n";
//Excelで読みたい値をheader,footerで囲む
echo $header;
echo $strCh;
echo $footer;
//確認用
echo "end";

これを実行すると
b.png
           ↓
    一瞬コンソールが立ち上がって
           ↓
a.png

こんな感じです。
やった感想としては

  • 言語特有のライブラリなんかを使えば利点はある(?)
  • とりあえず無理やりやった感があるのでもうちょっとスマートなやり方があるかも。
  • 文字コードよく分からん
  • VBAの配列よくわからん
31
25
3

Register as a new user and use Qiita more conveniently

  1. You get articles that match your needs
  2. You can efficiently read back useful information
  3. You can use dark theme
What you can do with signing up
31
25