1. 程式人生 > 實用技巧 >非常簡單實用的Excel匯出

非常簡單實用的Excel匯出

1,Html程式碼:建立匯出按鈕(使用的是EasyUI外掛)

<a href="javascript:void(0)" onclick="ExportSalesMaterialData()" class="easyui-linkbutton" data-options="iconCls:'icon-download',plain:true">匯出查詢資料</a></td>

2,JS程式碼

function ExportSalesMaterialData() {
            var rows = $('#dg').datagrid('getRows');//dg為Table標籤ID
            
if (rows.length > 0) { $.messager.confirm('確認', '確定匯出資料嗎?', function (v) { if (v) { $('#form1').form('submit', { url: "MBStatistics.aspx?action=excel&" + $("#form1").serialize(),//form1為form表單ID(例:<form id="form1" method="post"></form>) }); } }); }
else { $.messager.alert("提示", "當前沒有可匯出資料!"); } }

3,C# 程式碼

        public void ExportSalesMaterialData() 
        {
            StringBuilder filter = new StringBuilder();//這裡為對應表單where條件
            filter.Append(" 1=1 and IsDelete=0 ");//*
            if (!string.IsNullOrWhiteSpace(GetPam("
StartTime"))) { filter.AppendFormat(" and CreateTime >= '{0}'", GetPam("StartTime")); } if (!string.IsNullOrWhiteSpace(GetPam("EndTime"))) { filter.AppendFormat(" and CreateTime <= '{0}'", GetPam("EndTime")); } if (!string.IsNullOrWhiteSpace(GetPam("combProductStatusType"))) { filter.AppendFormat(" and IsRelated = '{0}'", GetPam("combProductStatusType")); } string where = filter.ToString();
//注意:你只需要改sqlStr引數的sql語句,改成你要匯出的sql即可
string sqlStr = string.Format(@" select CreateTime '日期',DrugUsersName '購藥人',DrugUsersPhone '手機號',WXNumber '微信', ConfirmedDisease '確診疾病',DrugName '藥品通用名',BrandName '藥品品牌',Specifications '急需藥品規格', Manufacturer '生產廠家', SurplusQuantity '剩餘藥品餘量',[Address] '藥品郵寄地址', Remake '備註', case IsRelated when 1 then '聯絡' else '無聯絡' end '是否聯絡' from ChronicDiseaseRegister WHERE {0} ORDER BY CreateTime desc ", where); string fileName = DateTime.Now.ToString(); Out2Excel(DAL.Base.SqlHelper.ExecuteDataSet("MallCenter", CommandType.Text, sqlStr).Tables[0], fileName); } private void Out2Excel(DataTable dtSource, string fileName) { HSSFWorkbook workbook = new HSSFWorkbook(); HSSFSheet sheet = workbook.CreateSheet() as HSSFSheet; HSSFRow dataRow = null; int sheetMaxRowIndex = 65535; int currentRowIndex = 0; //填充內容 for (int i = 0; i < dtSource.Rows.Count; i++) { if (currentRowIndex == 0) { //填充表頭 dataRow = sheet.CreateRow(currentRowIndex) as HSSFRow; foreach (DataColumn column in dtSource.Columns) { HSSFCell cell = dataRow.CreateCell(column.Ordinal) as HSSFCell; cell.SetCellValue(column.ColumnName); } currentRowIndex++; } dataRow = sheet.CreateRow(currentRowIndex) as HSSFRow; for (int j = 0; j < dtSource.Columns.Count; j++) { HSSFCell cell = dataRow.CreateCell(j) as HSSFCell; cell.CellStyle.DataFormat = HSSFDataFormat.GetBuiltinFormat("@"); cell.SetCellValue(dtSource.Rows[i][j].ToString()); } currentRowIndex++; if (currentRowIndex > sheetMaxRowIndex) { sheet = workbook.CreateSheet() as HSSFSheet; currentRowIndex = 0; } } //儲存 using (MemoryStream ms = new MemoryStream()) { workbook.Write(ms); Out2Client(ms, fileName); } } private void Out2Client(MemoryStream ms, string fileName) { byte[] data = ms.ToArray(); if (!fileName.Contains(".xls") || !fileName.Contains(".xlsx")) { fileName += ".xls"; } #region 客戶端儲存 HttpResponse response = HttpContext.Current.Response; HttpRequest request = HttpContext.Current.Request; response.Clear(); response.Charset = "UTF-8"; response.ContentEncoding = System.Text.Encoding.UTF8; response.ContentType = "application/vnd-excel";//"application/vnd.ms-excel"; if (request.UserAgent.ToLower().IndexOf("msie") > -1) { fileName = HttpUtility.UrlPathEncode(fileName); } if (request.UserAgent.ToLower().IndexOf("firefox") > -1) { response.AddHeader("Content-Disposition", "attachment;filename=\"" + fileName + "\""); } else { response.AddHeader("Content-Disposition", "attachment;filename=" + fileName); } response.AddHeader("Content-Length", data.Length.ToString()); response.BinaryWrite(data); response.End(); #endregion }

非常簡單易懂,複製即用