protected void Page_Load(object sender, EventArgs e) { //直接在bin add referece search Microsoft.Office.Interop.Excel.dll (.net 4.5 version 好像是是 1.4.0.0.0) string filePath = Request.MapPath(@"~\excel\someData.xlsx"); //excel文件路径(server path) string sheetName = "Sheet1"; //文件中,哪一个sheet string connectionString07 = String.Format("Provider=Microsoft.ACE.OLEDB.12.0;Data Source={0};Extended Properties='Excel 12.0;HDR=YES'", filePath); //string connectionString03 = String.Format("Provider=Microsoft.Jet.OLEDB.4.0;Data Source={0};Extended Properties=Excel 8.0", filePath); string query = String.Format("select * from [{0}$]", sheetName); OleDbConnection connection = new OleDbConnection(connectionString07); OleDbDataAdapter adapter = new OleDbDataAdapter(query, connectionString07); DataSet dataSet = new DataSet(); adapter.Fill(dataSet); DataTable table = dataSet.Tables[0]; }
注意 : 如果读取后要insert to SQL, 要注意格式和字的长度,把最长的放最上面,微软默认会依据前面8 rows来决定类型和长度等等。(如果遇到问题可以参考)
导出 excel 让游览器下载 (not ajax)
首先使用这个插件 http://epplus.codeplex.com/documentation (nuget可以下载)
更多功能介绍 : http://www.codeproject.com/Articles/680421/Create-Read-Edit-Advance-Excel-Report-in
然后 code :
using OfficeOpenXml;
public class Person { public string name { get; set; } public int age { get; set; } public bool isOK { get; set; } public DateTimeOffset dt { get; set; } public double dou { get; set; } } protected void Page_Load(object sender, EventArgs e) { try { List<Person> persons = new List<Person> { new Person { name = "keatkeat", age = 10,isOK = false,dt = DateTimeOffset.Now,dou = 50.66 }, new Person { name = "xinyao", age = 12,isOK = true,dt = DateTimeOffset.Now,dou = 50.00 } }; using (ExcelPackage pck = new ExcelPackage()) { //Create the worksheet ExcelWorksheet ws = pck.Workbook.Worksheets.Add("Demo"); ws.Cells["A1"].LoadFromCollection<Person>(persons, true); //load data from collection Response.Clear(); Response.AddHeader("content-disposition", "attachment; filename=file.xlsx"); //file name Response.ContentType = "application/vnd.openxmlformats-officedocument.spreadsheetml.sheet"; Response.BinaryWrite(pck.GetAsByteArray()); Response.End(); } } catch (Exception ex) { throw; } }
建议是开一个独立的 web form page 来处理,前端可以简单的用 window popup 来做下载 ^^
一些常用的 Excel 操作 :
merge & center
var cells = ws.Cells[1, 1, 1, 5]; //FromRow, FromColumn, ToRow, ToColumn , 是从1开始的不是0哦 cells.Merge = true; cells.Style.HorizontalAlignment = ExcelHorizontalAlignment.Center;