关于文件导入的问题,急!!!
我想要将客户端的excel文件中的内容导入到服务器端的数据库中,能不能实现?如何实现呢?
[解决办法]
/// <summary>
/// 将Excle数据导入数据库
/// Excle列名必须与要传入表的列名一致
/// </summary>
/// <param name="strPath">路径 </param>
/// <param name="strTableName">表名 </param>
public static int InTableFromExcel(string strPath,string strTableName)
{
SqlServerDbAccess m_SqlServerDbAccess = new SqlServerDbAccess();
OleDbConnection cnnxls = null;
OleDbCommand comm = null;
OleDbDataAdapter myda = null;
int x = 0;
int intOpinion = 0;
DataSet myds;
try
{
//读取Excel
string mystring = "Provider=Microsoft.Jet.OLEDB.4.0;" + "Data Source=" + strPath + ";" + "Extended Properties=Excel 8.0;";
cnnxls = new OleDbConnection(mystring);
comm = new OleDbCommand("select * from [sheet1$]", cnnxls);
myda = new OleDbDataAdapter(comm);
myds = new DataSet();
myda.Fill(myds);
//查看列名是否一直
string strOpinion = "SELECT TOP 0 * FROM " + strTableName;
DataSet ds = new DataSet();
ds = m_SqlServerDbAccess.executeDataSetCmdString(strOpinion);
System.Data.DataTable table = ds.Tables[0];
System.Data.DataTable excelTable = myds.Tables[0];
if (excelTable.Columns.Count > table.Columns.Count)
{
cnnxls.Close();
return 0;
}
foreach (DataColumn col in table.Columns)
{
for (int y = 0; y < excelTable.Columns.Count; y++)
{
if (col.ColumnName.Trim() == excelTable.Columns[y].ColumnName.Trim())
{
intOpinion++;
break;
}
}
}
if (intOpinion != excelTable.Columns.Count)
{
cnnxls.Close();
return 0;
}
//数据导入数据库
int intColumnCount = excelTable.Columns.Count;
string strColumnName = excelTable.Columns[0].ColumnName;
for (int i = 1; i < excelTable.Columns.Count; i++)
{
strColumnName += "," + excelTable.Columns[i].ColumnName;
}
string strCommText = string.Empty;
for (int i = 0; i < myds.Tables[0].Rows.Count; i++)
{
strCommText += " INSERT INTO " + strTableName + "(" + strColumnName + ") values ( '";
for (int j = 0; j < intColumnCount - 1; j++)
{
strCommText += myds.Tables[0].Rows[i].ItemArray[j].ToString() + "', '";
}
strCommText += myds.Tables[0].Rows[i].ItemArray[intColumnCount - 1].ToString() + "') ";
}
x = m_SqlServerDbAccess.executeNoQueryCmdString(strCommText);
cnnxls.Close();
}
catch (Exception ex)
{
cnnxls.Close();
}
finally
{
cnnxls.Close();
}
return x;
}