本篇是C# or Java 程式 利用 Powershell 開啟有密碼碼保護的Excel檔
C# Example:
class Program
{
static void Main(string[] args)
{
ProcessStartInfo psi = new ProcessStartInfo("powershell")
{
RedirectStandardInput = true,
CreateNoWindow = true,
UseShellExecute = false
};
using (var exeProcess = Process.Start(psi))
{
var input = exeProcess.StandardInput;
input.WriteLine("$path = \"D:\\monitor.xlsx\"");
input.WriteLine("$password = \"12345\"");
input.WriteLine("$excel = New-Object -ComObject Excel.Application");
input.WriteLine("$workbook = $excel.Workbooks.Open($path,$false,$false, 5,$password)");
input.WriteLine("$excel.Visible = $true");
}
}
}
Java Example
public class OpenExcel {
public static void main(String[] args) throws IOException {
// TODO Auto-generated method stub
String[] list = {"powershell.exe"};
ProcessBuilder pb = new ProcessBuilder(list);
pb.redirectOutput(ProcessBuilder.Redirect.INHERIT);
Process p = pb.start();
OutputStream out = p.getOutputStream();
PrintWriter pw = new PrintWriter(new BufferedWriter(new OutputStreamWriter(out)));
pw.println("$path = \"D:\\monitor.xlsx\"");
pw.println("$password = \"12345\"");
pw.println("$excel = New-Object -ComObject Excel.Application");
pw.println("$workbook = $excel.Workbooks.Open($path,$false,$false, 5,$password)");
pw.println("$excel.Visible = $true");
pw.close();
try {
p.waitFor();
p.destroy();
} catch(InterruptedException ex) {
}
}
}