[DllImport("User32.dll", CharSet = CharSet.Auto)]
public static extern int GetWindowThreadProcessId(IntPtr hwnd, out int ID);
[DllImport("kernel32.dll")]
public static extern int OpenProcess(int dwDesiredAccess, bool bInheritHandle, int dwProcessId);
public const int PROCESS_ALL_ACCESS = 0x1F0FFF;
public const int PROCESS_VM_READ = 0x0010;
public const int PROCESS_VM_WRITE = 0x0020;
public List<CaipiaoData> ReadDataFromXls(string path, int dataNum)
{
//定义句柄变量
IntPtr hwnd;
//定义进程ID变量
int pid = 0;
//读取excel
// int indexSheet = 1;
Microsoft.Office.Interop.Excel.ApplicationClass Myexcel =
new Microsoft.Office.Interop.Excel.ApplicationClass();
if (Myexcel == null)
{
return null;
}
Myexcel.Visible = false ;
Myexcel.DisplayAlerts = false;
Myexcel.UserControl = true;
object Nothing = System.Type.Missing;
Myexcel.Application.Workbooks.Open(path, Nothing, Nothing, Nothing, Nothing, Nothing,
Nothing, Nothing, Nothing, Nothing, Nothing, Nothing, Nothing, Nothing, Nothing);
Microsoft.Office.Interop.Excel.Workbooks wbs = Myexcel.Workbooks;
Microsoft.Office.Interop.Excel.Workbook wb = wbs[1];
Microsoft.Office.Interop.Excel.Worksheet ws = (Microsoft.Office.Interop.Excel.Worksheet)wb.Worksheets["Sheet1"];
List<CaipiaoData> datalist = new List<CaipiaoData>();
for (int i = 1; i < ws.Rows.Count; i++)
{
Microsoft.Office.Interop.Excel.Range rng3 = ws.get_Range("B" + i, Nothing);
if (rng3.Value2 == null)
{
break;
}
string str = rng3.Value2.ToString().Trim();
CaipiaoData cd = SlipData(str);
datalist.Add(cd);
}
//获取Excel App的句柄
hwnd = new IntPtr(Myexcel.Hwnd);
//通过Windows API获取Excel进程ID
GetWindowThreadProcessId(hwnd, out pid);
try
{
wb.Close(Microsoft.Office.Interop.Excel.XlSaveAction.xlDoNotSaveChanges,
path, false);
Myexcel.Quit();
}
catch (Exception)
{
//正常退出Excel失败,可以记录一下日志.
}
finally
{
//强制结束Excel进程
if (Myexcel != null && pid > 0)
{
int ExcelProcess;
ExcelProcess = OpenProcess(PROCESS_VM_READ | PROCESS_VM_WRITE, false, pid);
//判断进程是否仍然存在
if (ExcelProcess > 0)
{
try
{
//通过进程ID,找到进程
System.Diagnostics.Process process = System.Diagnostics.Process.GetProcessById(pid);
//Kill 进程
process.Kill();
}
catch (Exception)
{
}
}
}
}
return datalist;
}