//上传
protected void btnUpload_Click(object sender, EventArgs e) { string filePath = Server.MapPath("~/UploadFile"); if (fileUploadDatas.HasFile) { filePath =filePath + Guid.NewGuid().ToString("N") + Path.GetExtension(fileUploadDatas.FileName); fileUploadDatas.SaveAs(filePath); DataTable dt = ReadExcelToTable(filePath); } } //读取Excel到DataTable
private DataTable ReadExcelToTable(string path) { string connstring = "Provider=Microsoft.ACE.OLEDB.12.0;Data Source=" + path + ";Extended Properties='Excel 8.0;HDR=NO;IMEX=1';"; // Office 07,10 //string connstring = Provider=Microsoft.JET.OLEDB.4.0;Data Source=" + path + ";Extended Properties='Excel 8.0;HDR=NO;IMEX=1';"; //Office 03 using (OleDbConnection conn = new OleDbConnection(connstring)) { conn.Open(); DataTable sheetsName = conn.GetOleDbSchemaTable(OleDbSchemaGuid.Tables, new object[] { null, null, null, "Table" }); //string firstSheetName = sheetsName.Rows[0][2].ToString(); try { string sql = string.Format("SELECT * FROM [{0}]", "Template$");//firstSheetName); OleDbDataAdapter ada = new OleDbDataAdapter(sql, connstring); DataSet set = new DataSet(); ada.Fill(set); return set.Tables[0]; } catch { return new DataTable(); } } } //导出CSV的方法
public void ExportToCSV(string[] list) { string temp = string.Format("attachment;filename={0}", DateTime.Now.ToString("yyyyMMddHHmmss") + ".csv"); Response.ClearHeaders(); Response.AppendHeader("Content-disposition", temp); Response.ContentType = "application/unkown"; Response.ContentEncoding = Encoding.UTF8; StreamWriter sw = new StreamWriter(Response.OutputStream, Encoding.Default); foreach (string item in list) { sw.WriteLine(item); } sw.Close(); Response.End(); }