1.cs方法
/// <summary>
/// 得到Excle数据/// </summary>
/// <returns></returns>
private System.Data.DataTable GetDataTable()
{
DataSet ds = new DataSet();
string filepath = Server.MapPath("k.xls");
if (!File.Exists(filepath))
{
Page.RegisterClientScriptBlock("msg", "<script>alert('该文件不存在!')</script>");
}
else
{
string strConn = "Provider=Microsoft.Jet.OleDb.4.0;" + "data source=" + filepath + ";Extended Properties='Excel 8.0; HDR=YES; IMEX=1'";
OleDbConnection conn = new OleDbConnection(strConn);
OleDbDataAdapter odda = new OleDbDataAdapter("select * from [Sheet1$]", conn);
odda.Fill(ds);
int rowcount = ds.Tables[0].Rows.Count;
int colcount = ds.Tables[0].Columns.Count;
countnum = rowcount;
Excel.Application xlApp = new Excel.Application();
Excel.Workbooks w = xlApp.Workbooks;
Excel.Workbook workbook = w.Add(Excel.XlWBATemplate.xlWBATWorksheet);
Excel.Worksheet worksheet = (Excel.Worksheet)workbook.Worksheets[1];
for (int i = 0; i < ds.Tables[0].Columns.Count; i++)
{
worksheet.Cells[1, i + 1] = ds.Tables[0].Columns[i].ColumnName;
}
//写入数值
for (int r = 0; r < ds.Tables[0].Rows.Count; r++)
{
for (int i = 0; i < ds.Tables[0].Columns.Count; i++)
{
worksheet.Cells[r + 2, i + 1] = ds.Tables[0].Rows[r][i];
}
list_Client.Items.Add(ds.Tables[0].Rows[r][0].ToString());
}
}
return ds.Tables[0];
}