/// <summary>
/// 根据路径读取Excel放入DataTable里
/// </summary>
/// <param name="path"></param>
/// <param name="error"></param>
/// <returns></returns>
public DataTable ExcelToDS(string path,out string error)
{
string fileType = System.IO.Path.GetExtension(path);
string fileType1 = path.Substring(path.LastIndexOf('.'));
string strConn = "Provider=Microsoft.Jet.OLEDB.4.0;" + "Data Source=" + path + ";" + "Extended Properties=Excel 8.0;";
if (fileType == ".xls")
strConn = "Provider=Microsoft.Jet.OLEDB.4.0;" + "Data Source=" + path + ";" + ";Extended Properties=\"Excel 8.0;HDR=YES;IMEX=1\"";
else
strConn = "Provider=Microsoft.ACE.OLEDB.12.0;" + "Data Source=" + path + ";" + ";Extended Properties=\"Excel 12.0;HDR=YES;IMEX=1\"";
DataSet ds = null;
try
{
OleDbConnection conn = new OleDbConnection(strConn);
conn.Open();
string strExcel = "";
OleDbDataAdapter myCommand = null;
//得到所有sheet的名字
DataTable sheetsName = conn.GetOleDbSchemaTable(OleDbSchemaGuid.Tables, new object[] { null, null, null, "Table" });
//得到第一个sheet的名字
string firstSheetName = sheetsName.Rows[0][2].ToString();
strExcel = "select * from [sheet1$]";
myCommand = new OleDbDataAdapter(strExcel, strConn);
ds = new DataSet();
myCommand.Fill(ds, "table1");
error = "";
}
catch(Exception ex)
{
error = ex.Message;
}
return ds.Tables[0];
}
/// <summary>
/// 下载文件到指定路径
/// </summary>
/// <param name="filePath"></param>
/// <returns></returns>
public string Download(string filePath)
{
string path = fileP + Path.GetFileName(filePath);
// 设置参数
HttpWebRequest request = WebRequest.Create(filePath) as HttpWebRequest;
//发送请求并获取相应回应数据
HttpWebResponse response = request.GetResponse() as HttpWebResponse;
//直到request.GetResponse()程序才开始向目标网页发送Post请求
Stream responseStream = response.GetResponseStream();
//创建本地文件写入流
Stream stream = new FileStream(path, FileMode.Create);
byte[] bArr = new byte[1024];
int size = responseStream.Read(bArr, 0, (int)bArr.Length);
while (size > 0)
{
stream.Write(bArr, 0, size);
size = responseStream.Read(bArr, 0, (int)bArr.Length);
}
stream.Close();
responseStream.Close();
return path;
}
Excel导入---后台下载
最新推荐文章于 2020-02-07 18:43:55 发布