com调用excel后,进程未关闭解决方案

COM调用结束后,进程未关闭

1. c++ com

  • C++直接调用com的,可以通过Application::GetHwnd()获取窗口句柄,之后通过窗口句柄获取进程pid,然后kill进程,参考下面函数LuaCloseWindow()内代码。

2. luacom

  • 注册lua函数,在lua中调用该函数。
static int LuaCloseWindow(lua_State* L)
{
	long hWnd = luaL_checkinteger(L, 1);
	unsigned long dwPid = 0;
	::GetWindowThreadProcessId((HWND)hWnd, &dwPid);
	char cmdData[128] = { 0 };
	sprintf_s(cmdData, "/c taskkill /F /PID %d /T", dwPid);

	ShellExecute(NULL, "open", "cmd", cmdData, NULL, SW_HIDE);
	return 0;
}

lua_register(L, "CloseWindow", LuaCloseWindow);
  • 在lua代码中获取excel窗口句柄,调用CloseWindow()关闭进程
require('luacom')
local iconv = require('luaiconv')

local iconvGbk2Utf8 = iconv.new("utf-8", "gbk")
function gbk2utf8(str)
    return iconvGbk2Utf8:iconv(str)
end

local iconvUtf82Gbk = iconv.new("gbk", "utf-8")
function utf82GBK(str)
    return iconvUtf82Gbk:iconv(str)
end

function IsFileExists(path)
    local file = io.open(path, "rb")
    if file then file:close() end
    return file ~= nil
  end

-- 获取excel内容
function GetContent( strFilePath )
    local excel = luacom.CreateObject("Excel.Application")
    if excel == nil then
        excel = luacom.CreateObject("Ket.Appplication")
    end
    assert(excel ~= nil, "Neither Excel nor WPS is installed. Please install and try again.")
    excel.Visible = false
    assert(IsFileExists(strFilePath),"\""..strFilePath.."\",No Such File! ")
    strFilePath = gbk2utf8(strFilePath)
    local book = excel.WorkBooks:Open(strFilePath,0,1)  --ReadOnly open
    assert(book ~= nil, "Open "..strFilePath.." Failed")
    local sheet = book.ActiveSheet
	assert(sheet ~= nil, "empty sheet!")
    local nColCount =sheet.UsedRange.Columns.Count
    local nRowCount =sheet.UsedRange.Rows.Count
    local tbExcelData = {}
    for nRow = 1, nRowCount do
        local tbRowData = {}
        for nCol = 1, nColCount do
            local str = tostring(sheet.Cells(nRow,nCol).Value2)
            str = utf82GBK(str)
            str = string.gsub(str,"\n","")
            if str == "nil" then
                str = ""
            end
            table.insert(tbRowData,str)
        end
        table.insert(tbExcelData,tbRowData)
    end
    --close File
    excel.DisplayAlerts = false
	book:Close()
    CloseWindow(excel.hWnd) --获取excel窗口句柄,通过excel句柄关闭进程
    --[[
	book:Close()
	sheet = nil
	book = nil
    excel:Quit()
	excel = nil
    collectgarbage()
    ]]--
    return tbExcelData,nRowCount,nColCount
end

luaDll,luacom,luaiconv下载,请点击这里

  • 0
    点赞
  • 0
    收藏
    觉得还不错? 一键收藏
  • 打赏
    打赏
  • 3
    评论
评论 3
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包

打赏作者

Finn Wang

你的鼓励将是我创作的最大动力

¥1 ¥2 ¥4 ¥6 ¥10 ¥20
扫码支付:¥1
获取中
扫码支付

您的余额不足,请更换扫码支付或充值

打赏作者

实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值