C# 調用 SQL 存儲過程(傳中文參數亂碼解決,SQL字符串拼接執行異常)

C#後臺代碼: 

   //<!---- start laizhixue 2019.06.18 ---->
        //導出自定義數據的Excel數據		
        public class ReturnMsg {
            public string ReturnState { get; set; }
            public string Url { get; set; }
            public string Message { get; set; }
            public int DeleteTime { get; set; }
        }

        //鎖
        private static readonly object Lock = new object();

        //服務器生成文件
        public JsonResult ExportMyExcel(string ProcSetName, string StartDate1, string EndDate1, string StartDate2, string EndDate2)
        {
            lock (Lock)
            {
                var returnMsg = new ReturnMsg();
                string conStr = System.Web.Configuration.WebConfigurationManager.ConnectionStrings["aZaaSFramework"].ToString();
                var list = new List<List<string>>();
                //調用存儲過程拉取相應的數據
                try
                {
                    //NPOI
                    string bookpath = Server.MapPath("~\\Content\\");                     //下載文件保存總目錄
                    string tempName = ProcSetName.Replace("/", "_");                      //特殊符號替換,防止異常
                    string bookName = tempName + DateTime.Now.ToString("yyyyMMddHHmmssfff") + ".xls";                         //文件名稱
                    string filepath = bookpath + bookName;                                //路徑
                    int dataNum = 0;                                                      //返回數據的數量

                    //SQL
                    DataSet ds = new DataSet();
                    SqlConnection con = new SqlConnection(conStr);
                    con.Open();
                    SqlCommand command = new SqlCommand("ExportMyExcel", con);
                    command.CommandType = CommandType.StoredProcedure;//採用存儲過程
                    command.Parameters.Add("@ProcSetName", SqlDbType.NVarChar, 100);//流程名字
                    command.Parameters["@ProcSetName"].Value = ProcSetName;

                    command.Parameters.Add("@StartDate1", SqlDbType.NVarChar, 100);//發起開始日期
                    if (!string.IsNullOrEmpty(StartDate1))
                    {
                        command.Parameters["@StartDate1"].Value = StartDate1 + " 00:00:00";
                    }
                    else {
                        command.Parameters["@StartDate1"].Value = StartDate1;
                    }

                    command.Parameters.Add("@EndDate1", SqlDbType.NVarChar, 100);//發起結束日期
                    if (!string.IsNullOrEmpty(EndDate1))
                    {
                        command.Parameters["@EndDate1"].Value = EndDate1 + " 23:59:59";
                    }
                    else
                    {
                        command.Parameters["@EndDate1"].Value = EndDate1 ;
                    }

                    command.Parameters.Add("@StartDate2", SqlDbType.NVarChar, 100);//完成開始日期
                    if (!string.IsNullOrEmpty(StartDate2))
                    {
                        command.Parameters["@StartDate2"].Value = StartDate2 + " 00:00:00";
                    }
                    else
                    {
                        command.Parameters["@StartDate2"].Value = StartDate2;
                    }
                  
                    command.Parameters.Add("@EndDate2", SqlDbType.NVarChar, 100);//完成結束日期
                    if (!string.IsNullOrEmpty(EndDate2))
                    {
                        command.Parameters["@EndDate2"].Value = EndDate2 + " 23:59:59";
                    }
                    else
                    {
                        command.Parameters["@EndDate2"].Value = EndDate2 ;
                    }

                    command.Parameters.Add("@Status", SqlDbType.TinyInt);//狀態
                    command.Parameters["@Status"].Value = 3;//完成

                    SqlDataAdapter adapter = new SqlDataAdapter(command);
                    adapter.Fill(ds);
                   
                    if (ds != null && ds.Tables.Count > 0)
                    {
                        //獲取數據條數
                        dataNum = ds.Tables.Count;

                        //創建workbook
                        HSSFWorkbook book = new HSSFWorkbook();

                        //創建Sheet1
                        ISheet sheet = book.CreateSheet("Sheet1");

                        //表頭
                        IRow headrow = sheet.CreateRow(0);

                        //添加表頭數據
                        for (var i = 0; i < ds.Tables[0].Columns.Count; i++)
                        {
                            ICell headcell = headrow.CreateCell(i);
                            headcell.SetCellValue(ds.Tables[0].Columns[i].ToString());
                            sheet.AutoSizeColumn(i);
                        }

                        //添加主數據  i行j列
                        for (var i = 0; i < ds.Tables[0].Rows.Count; i++)
                        {
                            //數據
                            IRow row = sheet.CreateRow(i + 1);
                            for (var j = 0; j < ds.Tables[0].Columns.Count; j++)
                            {
                                ICell cell = row.CreateCell(j);
                                //狀態轉中文
                                if (j == 0)
                                {
                                    switch (ds.Tables[0].Rows[i][j].ToString())
                                    {
                                        case "0":
                                            cell.SetCellValue("錯誤");
                                            break;
                                        case "1":
                                            cell.SetCellValue("處理中");
                                            break;
                                        case "2":
                                            cell.SetCellValue("進行中");
                                            break;
                                        case "3":
                                            cell.SetCellValue("已完成");
                                            break;
                                        case "4":
                                            cell.SetCellValue("已停止");
                                            break;
                                        case "5":
                                            cell.SetCellValue("已刪除");
                                            break;
                                    }
                                }
                                else
                                {
                                    cell.SetCellValue(ds.Tables[0].Rows[i][j].ToString());
                                }
                            }
                        }
                        //獲取當前列的寬度,然後對比本列的長度,取最大值
                        //自適應寬度
                        for (int columnNum = 0; columnNum < ds.Tables[0].Columns.Count; columnNum++)
                        {
                            int columnWidth = sheet.GetColumnWidth(columnNum) / 256;
                            for (int rowNum = 0; rowNum < sheet.LastRowNum; rowNum++)
                            {
                                IRow currentRow;
                                //當前行未被使用過
                                if (sheet.GetRow(rowNum) == null)
                                {
                                    currentRow = sheet.CreateRow(rowNum);
                                }
                                else
                                {
                                    currentRow = sheet.GetRow(rowNum);
                                }

                                if (currentRow.GetCell(columnNum) != null)
                                {
                                    ICell currentCell = currentRow.GetCell(columnNum);
                                    int length = Encoding.Default.GetBytes(currentCell.ToString()).Length;
                                    if (columnWidth < length)
                                    {
                                        columnWidth = length;
                                    }
                                }
                            }
                            sheet.SetColumnWidth(columnNum, columnWidth * 256);
                        }
                        // 寫入到服務器,需要下載到本地需要通過前臺的超鏈接
                        using (System.IO.MemoryStream ms = new System.IO.MemoryStream())
                        {
                            book.Write(ms);

                            using (FileStream fs = new FileStream(filepath, FileMode.Create, FileAccess.ReadWrite))
                            {
                                byte[] d = ms.ToArray();
                                fs.Write(d, 0, d.Length);
                                fs.Flush();
                            }
                            book = null;
                            ds.Dispose();
                        }
                        returnMsg.ReturnState="S";
                        returnMsg.Message = "導出成功!\n若已打開文件,數據則不會覆蓋之前已存在的文件!";
                        returnMsg.Url="/Content/" + bookName;
                        returnMsg.DeleteTime = GetDeleteTime(dataNum);
                        return Json(returnMsg);
                    }
                    else
                    {
                        returnMsg.ReturnState = "E";
                        returnMsg.Message = "請檢查ExportMyExcel存儲過程是否已完善代碼!";
                        return Json(returnMsg);
                    }
                }
                catch
                {
                    returnMsg.ReturnState = "E";
                    returnMsg.Message = "調用ExportMyExcel存儲過程異常!";
                    return Json(returnMsg);
                }
            }
        }

        //刪除服務器生成的文件
        public string DeleteFile(string Url)
        {
            try
            {
                FileInfo resFile = new FileInfo(Server.MapPath("~\\" + Url));//服務器的資源文件
                if (resFile.Exists)
                {
                    resFile.Delete();
                }
            }
            catch (Exception e)
            {
                System.Diagnostics.Debug.WriteLine("刪除文件異常!");
                return "error";
            }
            return "success";
        }

        //返回時間  毫秒為單位
        public int GetDeleteTime(int DataNum) {
            int time = 1;

            if (DataNum >=0 && DataNum <= 500)
            {
                time = 1;
            }
            else if (DataNum <= 3000)
            {
                time = 2;
            }
            else if (DataNum <= 6000)
            {
                time = 6;
            }
            else if (DataNum <= 10000)
            {
                time = 8;
            }
            else if (DataNum > 10000)
            {
                time = 12;
            }
            return time*1000;
        }

        //<!---- End laizhixue 2019.06.18 ---->

SQL存儲過程代碼: 

USE [aZaaS.Framework]
GO
/****** Object:  StoredProcedure [dbo].[ExportMyExcel]    Script Date: 09/10/2019 08:46:47 ******/
SET ANSI_NULLS ON
GO
SET QUOTED_IDENTIFIER ON
GO
--獲取需要導出的相應流程的表格數據
ALTER procedure [dbo].[ExportMyExcel]
@ProcSetName nvarchar(100),--流程名
@StartDate1 nvarchar(100),--發起開始日期
@EndDate1 nvarchar(100),--發起結束日期
@StartDate2 nvarchar(100),--完成開始日期
@EndDate2 nvarchar(100),--完成結束日期
@Status nvarchar(100)--狀態
AS
DECLARE @sql NVARCHAR(max)
BEGIN
	--類型必須為 NVARCHAR ,否則中文亂碼
	DECLARE @SQLFilterStr NVARCHAR(max)= ''
	
	--是否添加統一的SQL條件 1=是 0=否  默認1
    DECLARE @IfAddUnityStrFlag INT=1;
    
    IF @ProcSetName=N'供應商主檔流程'
    BEGIN
			--合併新增與更新的數據
		 	SET @SQLFilterStr=N'SELECT 
		 	kp.Status as 狀態
			,kp.FinishDate as 完成時間
			,ks.FormId as 流程編號
			,[Before_SupplierNo] as 供應商編號
			,[NewOrOldSel] as SAP系統
			,[Before_SupplierName] as 供應商名稱
			,[Before_VendorClass1] as 類別代碼1
			,[Before_VendorClass2] as 類別代碼2
			,[Before_SearchCondition] as 搜索條件
			,[Before_Country] as 國家
			,[Before_Address_1] as 街道1
			,[Before_Address_2] as 街道2
			,[Before_Address_3] as 街道3
			,[Before_PhoneNo_1] as 電話
			,[Before_FaxNo] as 傳真
			,[Before_E_email] as 電子信箱
			,[Before_HeadOffice] as 總部
			,[Before_Currency] as 訂單貨幣 
			,[Before_PaymentRule] as 前付款條件 
			,[Before_Trade1] as 國貿條件1 
			,[Before_Trade2] as 國貿條件2 
			,[Before_Seller] as 銷售員 
			,[Before_SellTel] as 銷售電話 
			,[Before_Remarks] as 備注 
			FROM 表名
			IF @StartDate1 <> ''
			BEGIN
				SET @SQLFilterStr=@SQLFilterStr+' and kp.StartDate >='''+@StartDate1+'''';
			END
			IF @EndDate1 <> ''
			BEGIN
				SET @SQLFilterStr=@SQLFilterStr+' and kp.StartDate <='''+@EndDate1+'''';
			END
	
			SET @IfAddUnityStrFlag=0;
    END
    IF @ProcSetName=N'生產單據取消/更改流程'
    BEGIN
	    --特殊處理 SELECT 前面加N,否則報錯
		SET @SQLFilterStr=N'SELECT
							 kp.Status as 狀態,
							 kp.FinishDate as 完成時間,
							 ks.FormId as 流程編號,
							 ZNUMBER as 單據號碼,
							 AUFNR as 工單號碼
					   FROM 表名
							 where kp.Folio like N''%'+@ProcSetName+'%'' and kp.Folio is             
                    not null and kp.Folio <> ''''' ;
    END
	
	--是否追加統一的條件
	IF(@IfAddUnityStrFlag=1)
	BEGIN
		IF @StartDate1 <> ''
		BEGIN
			SET @SQLFilterStr=@SQLFilterStr+' and kp.StartDate >='''+@StartDate1+'''';
		END
		IF @EndDate1 <> ''
		BEGIN
			SET @SQLFilterStr=@SQLFilterStr+' and kp.StartDate <='''+@EndDate1+'''';
		END
		IF @StartDate2 <> ''
		BEGIN
			SET @SQLFilterStr=@SQLFilterStr+' and kp.FinishDate >='''+@StartDate2+'''';
		END
		IF @EndDate2 <> ''
		BEGIN
			SET @SQLFilterStr=@SQLFilterStr+' and kp.FinishDate <= '''+@EndDate2+'''';
		END
	END
	
	IF(@SQLFilterStr <> '')
	BEGIN
		EXEC (@SQLFilterStr);
	END
END

SQL調用存儲過程:

EXECUTE [dbo].[ExportMyExcel] 
@ProcSetName=N'生產單據取消/更改流程',@StartDate1='',@EndDate1='',
@StartDate2='2018-01-01 00:00:00',@EndDate2='2019-09-10 00:00:00',@Status='3'

運行結果:

發表評論
所有評論
還沒有人評論,想成為第一個評論的人麼? 請在上方評論欄輸入並且點擊發布.
相關文章