Excel.Application exc = null;
Workbooks workBooks = null;
Workbook workBook = null;
Worksheet workSheet = null;
string strValue = "";
Excel.Range r = null;
System.Data.DataTable dt = new System.Data.DataTable();
DataRow myRow;
object oMissing = System.Reflection.Missing.Value;
try
{
exc = new Excel.Application();
exc.UserControl = true;
exc.Application.Workbooks.Open(path, oMissing, oMissing, oMissing, oMissing, oMissing, oMissing, oMissing, oMissing, oMissing, oMissing, oMissing, oMissing, oMissing, oMissing);
workBooks = exc.Workbooks;
workBook = workBooks[1];
workSheet = (Worksheet)workBook.Worksheets[1];
int colCount = workSheet.UsedRange.Columns.Count; //获得列数
int rowCount = workSheet.UsedRange.Rows.Count; //获得行数
//获取字段名称
for (int k = 1; k <= colCount; k++)
{
r = (Excel.Range)workSheet.Cells[1, k];
strValue = r.Text.ToString().Trim();
dt.Columns.Add(strValue, System.Type.GetType("System.String"));
}
//获取内容
for (int i = 2; i <= rowCount; i++)
{
myRow = dt.NewRow();
for (int j = 1; j <= colCount; j++)
{
//取excel单元格中的值
r = (Excel.Range)workSheet.Cells[i, j];
strValue = r.Text.ToString().Trim();
myRow[j - 1] = strValue;
}
dt.Rows.Add(myRow);
}
//关闭当前的excel进程
exc.Application.Workbooks.Close();
exc.Quit();
System.Runtime.InteropServices.Marshal.ReleaseComObject(exc);
exc = null;
IntPtr t = new IntPtr(exc.Hwnd);
int kid = 0;
GetWindowThreadProcessId(t, out kid);
System.Diagnostics.Process p = System.Diagnostics.Process.GetProcessById(kid);
p.Kill();
}
catch { }
return dt;
}
}
}