110,535
社区成员
发帖
与我相关
我的任务
分享
public DataTable GetExcelToDataTableBySheet(string FileFullPath, string SheetName)
{
//string strConn = "Provider=Microsoft.Jet.OleDb.4.0;" + "data source=" + FileFullPath + ";Extended Properties='Excel 8.0; HDR=NO; IMEX=1'"; //此连接只能操作Excel2007之前(.xls)文件
string strConn = "provider=Microsoft.ACE.OLEDB.12.0;data source=" + FileFullPath + "; Extended Properties='Excel 12.0 Xml;HDR=YES;IMEX=1'";
OleDbConnection conn = new OleDbConnection(strConn);
conn.Open();
DataSet ds = new DataSet();
OleDbDataAdapter odda = new OleDbDataAdapter(string.Format("SELECT * FROM [{0}]", SheetName), conn); //("select * from [Sheet1$]", conn);
int count = odda.Fill(ds, SheetName);
conn.Close();
return ds.Tables[0];
}
/// <summary>
/// 解析Excel,返回DataTable
/// </summary>
/// <param name="fileName"></param>
/// <returns></returns>
public static System.Data.DataTable ImpExcel(string fileName)
{
System.Data.DataTable dt = new System.Data.DataTable();
try
{
Microsoft.Office.Interop.Excel.Application app;
Workbooks wbs;
Worksheet ws;
app = new Microsoft.Office.Interop.Excel.Application();
wbs = app.Workbooks;
wbs.Add(fileName);
ws = (Worksheet)app.Worksheets.get_Item(1);
int a = ws.Rows.Count;
int b = ws.Columns.Count;
string name = ws.Name;
for (int i = 1; i <RowCount; i++)
{
DataRow dr = dt.NewRow();
for (int j = 1; j <= ColumnsCount; j++)
{
Range range = ws.get_Range(app.Cells[i, j], app.Cells[i, j]);
range.Select();
dr[j - 1] = app.ActiveCell.Text.ToString();
}
dt.Rows.Add(dr);
}
KillProcess(app);
return dt;
}
catch (Exception ex)
{
MessageBox.Show("数据绑定Excel失败! 失败原因:Excel格式不正确!", "提示信息", MessageBoxButtons.OK, MessageBoxIcon.Information);
return dt;
}
}