Register Register Member Login Member Login Member Login Forgot Password ??
PHP , ASP , ASP.NET, VB.NET, C#, Java , jQuery , Android , iOS , Windows Phone
 

Registered : 109,027

HOME > .NET Framework > Forum > ปัญหาการ Download excel file จากการ generate โดยใช้ EPPLUS บน C# ASP.NET .NET FrameWork 4.6.1



 

ปัญหาการ Download excel file จากการ generate โดยใช้ EPPLUS บน C# ASP.NET .NET FrameWork 4.6.1

 



Topic : 134989



โพสกระทู้ ( 11 )
บทความ ( 0 )



สถานะออฟไลน์




ผมกำลังหาวิธีการ Export excel file จากข้อมูลใน DB โดยใช้ EPPLUS ตอนนี้สามารถ Download file ได้ แต่ไม่สาสารถอ่าน file ได้ครับ

Excel file not valid

ส่วนนี้เป็น Code ฝั่ง script ที่ผมใช้ครับ

Code (JavaScript)
$.ajax({
            type: "POST",
            crossOrigin: true,
            url: "/api/Transaction/ExportExcel",
            headers: {
                Accept: "application/vnd.openxmlformats-officedocument.spreadsheetml.sheet",
            },
            data: {
                "Date_1": dateTime[0],
                "Date_2": dateTime[2],
                "PaymentType": (paymentType === "99" ? '' : paymentType),
                "Status": (paymentStatus === "99" ? '' : paymentStatus),
                "Outtrade": refNo,
                "Merchant": (merchantName == "00" ? '' : merchantName),
                "TerminalID": terminalId
            },
            success: function (result) {

                if (dateTime[0] == dateTime[2]) {
                    filename = "Transaction_Detail_" + dateTime[0].replace(/\//g, '-') + ".xlsx";
                }
                else {
                    filename = "Transaction_Detail_" + dateTime[0].replace(/\//g, '-') + " - " + dateTime[2].replace(/\//g, '-') + ".xlsx";
                }

                var uri = 'data:application/vnd.openxmlformats-officedocument.spreadsheetml.sheet,' + result;
                var link = document.createElement("a");
                link.href = uri;
                link.style = "visibility:hidden";
                link.download = filename;
                document.body.appendChild(link);
                link.click();
                document.body.removeChild(link); 
            },
            error: function (jqXHR, exception) {
                console.log("Post error");
                $('#btnApply').removeAttr("disabled");
                $('#btnExportExcel').removeAttr("disabled");
                getErrorMessage(jqXHR, exception);
            }
        });
        return deferred.promise();
    });


ส่วนนี้เป็น Code ฝั่ง Web API ที่ผมใช้ครับ

Code (C#)
public class TransactionController : ApiController
{
        [AllowAnonymous]
        [HttpPost]
        [Route("api/Transaction/ExportExcel")]
        public HttpResponseMessage ExportExcel(TransactionSearchReq req)
        {
            TransactionMgr transaction = new TransactionMgr();
            List<TransactionRecordRes> transactionList = new List<TransactionRecordRes>();
            HttpResponseMessage response = Request.CreateResponse(HttpStatusCode.OK);
            //MediaTypeHeaderValue mediaType = MediaTypeHeaderValue.Parse("application/octet-stream");
            MediaTypeHeaderValue mediaType = MediaTypeHeaderValue.Parse("application/vnd.openxmlformats-officedocument.spreadsheetml.sheet");
            //response.Content = new StringContent("hello", Encoding.Unicode);
            byte[] fileContents;
            string fileName;
            try
            {
                // Get transaction records
                transactionList = transaction.GetSearchTransactionRecord(req);
                if (transactionList.Count() > 0)
                {
                    ExcelPackage.LicenseContext = LicenseContext.NonCommercial;
                    //var contentType = "application/vnd.openxmlformats-officedocument.spreadsheetml.sheet";
                    using (var package = new ExcelPackage())
                    {
                        var worksheet = package.Workbook.Worksheets.Add("Sheet1");

                        // Put whatever you want here in the sheet
                        worksheet.Cells["A1"].Value = "Date Time";
                        worksheet.Cells["A1"].Style.Font.Size = 12;
                        worksheet.Cells["A1"].Style.Font.Bold = true;
                        worksheet.Cells["A1"].Style.Border.Top.Style = ExcelBorderStyle.Hair;

                        worksheet.Cells["B1"].Value = "Merchant Name";
                        worksheet.Cells["B1"].Style.Font.Size = 12;
                        worksheet.Cells["B1"].Style.Font.Bold = true;
                        worksheet.Cells["B1"].Style.Border.Top.Style = ExcelBorderStyle.Hair;

                        worksheet.Cells["C1"].Value = "Terminal ID";
                        worksheet.Cells["C1"].Style.Font.Size = 12;
                        worksheet.Cells["C1"].Style.Font.Bold = true;
                        worksheet.Cells["C1"].Style.Border.Top.Style = ExcelBorderStyle.Hair;

                        worksheet.Cells["D1"].Value = "Payment Type";
                        worksheet.Cells["D1"].Style.Font.Size = 12;
                        worksheet.Cells["D1"].Style.Font.Bold = true;
                        worksheet.Cells["D1"].Style.Border.Top.Style = ExcelBorderStyle.Hair;

                        worksheet.Cells["E1"].Value = "Outtrade";
                        worksheet.Cells["E1"].Style.Font.Size = 12;
                        worksheet.Cells["E1"].Style.Font.Bold = true;
                        worksheet.Cells["E1"].Style.Border.Top.Style = ExcelBorderStyle.Hair;

                        worksheet.Cells["F1"].Value = "Amount";
                        worksheet.Cells["F1"].Style.Font.Size = 12;
                        worksheet.Cells["F1"].Style.Font.Bold = true;
                        worksheet.Cells["F1"].Style.Border.Top.Style = ExcelBorderStyle.Hair;

                        worksheet.Cells["G1"].Value = "Status";
                        worksheet.Cells["G1"].Style.Font.Size = 12;
                        worksheet.Cells["G1"].Style.Font.Bold = true;
                        worksheet.Cells["G1"].Style.Border.Top.Style = ExcelBorderStyle.Hair;

                        for (int i = 0; i < transactionList.Count(); i++)
                        {
                            worksheet.Cells[i + 2, 1].Value = transactionList[i].DateTime;
                            worksheet.Cells[i + 2, 2].Value = transactionList[i].Merchant;
                            worksheet.Cells[i + 2, 3].Value = transactionList[i].TerminalID;
                            worksheet.Cells[i + 2, 4].Value = transactionList[i].PaymentType;
                            worksheet.Cells[i + 2, 5].Value = transactionList[i].Outtrade;
                            worksheet.Cells[i + 2, 6].Value = transactionList[i].Amount;
                            worksheet.Cells[i + 2, 7].Value = transactionList[i].Status;
                        }

                        // So many things you can try but you got the idea.
                        // Finally when you're done, export it to byte array.
                        fileContents = package.GetAsByteArray();
                    }

                    if (fileContents == null || fileContents.Length == 0)
                    {
                        response = Request.CreateResponse(HttpStatusCode.InternalServerError);
                        response.Content = new StringContent("Export file error.", Encoding.Unicode);
                        //return NotFound();
                        return response;
                    }
                    else
                    {
                        if (string.Compare(req.Date_1, req.Date_2) == 0)
                        {
                            fileName = string.Format("Transaction_Detail_{0}.xlsx", req.Date_1.Replace('/', '-'));
                        }
                        else
                        {
                            fileName = string.Format("Transaction_Detail_{0} - {1}.xlsx", req.Date_1.Replace('/', '-'), req.Date_2.Replace('/', '-'));
                        }

                        //return File( fileContents, contentType, fileName );
                        MemoryStream memoryStream = new MemoryStream(fileContents);
                        response.Content = new StreamContent(memoryStream);
                        response.Content.Headers.ContentType = mediaType;
                        response.Content.Headers.ContentDisposition =
                            new ContentDispositionHeaderValue("attachment") { FileName = fileName };
                        return response;
                    }
                }
                else
                {
                    response = Request.CreateResponse(HttpStatusCode.InternalServerError);
                    response.Content = new StringContent("Export file error.", Encoding.Unicode);
                    //return NotFound();
                    return response;
                }
            }
            catch (Exception ex)
            {
                response = Request.CreateResponse(HttpStatusCode.InternalServerError);
                response.Content = new StringContent("Export file error.", Encoding.Unicode);
                //return NotFound();
                return response;
            }
        }
}


อยากทราบว่าปัญหาเกิดจากอะไร และรบกวนขอวิธีแก้ปัญหาด้วยครับ
ขอบคุณครับ



Tag : .NET, jQuery, Excel (Excel.Application), Web (ASP.NET), Web API, MVC







Move To Hilight (Stock) 
Send To Friend.Bookmark.
Date : 2020-03-12 11:25:34 By : muramasa.shin View : 1476 Reply : 7
 

 

No. 1



โพสกระทู้ ( 1,458 )
บทความ ( 0 )



สถานะออฟไลน์
Twitter Facebook Blogger

ContentType ลองเปลี่ยนเป็น "application/vnd.ms-excel" ดูครับ

และ/หรือ

เปลี่ยน/เพิ่ม(Header) content-disposition เป็น "attachment;filename=ชื่อไฟล์.xlsx"


อันที่สองเพิ่งเห็นว่ามีแล้ว








ประวัติการแก้ไข
2020-03-12 12:08:30
2020-03-12 12:10:04
แสดงความคิดเห็นโดยอ้างถึง ความคิดเห็นนี้
Date : 2020-03-12 12:07:32 By : PhrayaDev
 


 

No. 2



โพสกระทู้ ( 11 )
บทความ ( 0 )



สถานะออฟไลน์


ตอบความคิดเห็นที่ : 1 เขียนโดย : PhrayaDev เมื่อวันที่ 2020-03-12 12:07:32
รายละเอียดของการตอบ ::
ลองเปลี่ยนเเล้วครับ เเต่ยังไม่ได้เหมือนเดิมครับ

แสดงความคิดเห็นโดยอ้างถึง ความคิดเห็นนี้
Date : 2020-03-12 13:12:00 By : muramasa.shin
 

 

No. 3



โพสกระทู้ ( 9,559 )
บทความ ( 2 )



สถานะออฟไลน์


ลองเช็ค file ดูก่อนไหมครับ เห็น error บอกว่า ผิด format หรือไฟล์เสีย
และตรวจเช็ค version ของ .xlsx ด้วยครับ และ/หรือ เครื่องนี้ใช้ได้แค่ .xls

ปล. เครื่องนี้ server ใช้ os อะไรครับ
ได้ลง office ไว้ไหม version อะไร


ประวัติการแก้ไข
2020-03-12 14:28:58
2020-03-12 14:29:45
แสดงความคิดเห็นโดยอ้างถึง ความคิดเห็นนี้
Date : 2020-03-12 14:27:42 By : Chaidhanan
 


 

No. 4



โพสกระทู้ ( 11 )
บทความ ( 0 )



สถานะออฟไลน์


ตอบความคิดเห็นที่ : 3 เขียนโดย : Chaidhanan เมื่อวันที่ 2020-03-12 14:27:42
รายละเอียดของการตอบ ::
ผมใช้ Windows 10 Pro ลง office ไว้เป็น version: 2016 ครับ

แสดงความคิดเห็นโดยอ้างถึง ความคิดเห็นนี้
Date : 2020-03-12 16:21:22 By : muramasa.shin
 


 

No. 5



โพสกระทู้ ( 9,559 )
บทความ ( 2 )



สถานะออฟไลน์


ตรวจสอบ reference ดูอีกที่ครับ อ้างอิง library ของ office 2016 จริงหรือเปล่า บางทีอ้างอิง ผิด library
แสดงความคิดเห็นโดยอ้างถึง ความคิดเห็นนี้
Date : 2020-03-12 16:56:02 By : Chaidhanan
 


 

No. 6

Guest


@ เจ้าของกระทู้

คุณมั่นใจแค่ไหน return deferred.promise();


ผมเข้าใจ TypeScript/JavaScript ไม่ได้มากไปกว่าคุณ

Code (JavaScript)
async function fuckAjax(fuck) {
    return $.ajax({
        url: 'your/meThod/'+fuck,
        type: 'get',
        dataType: 'json',
    })
    .then(response => response.data);
}

let fuckAgain = await fuckAjax('data');

แสดงความคิดเห็นโดยอ้างถึง ความคิดเห็นนี้
Date : 2020-03-14 13:28:49 By : หน้าฮี
 


 

No. 7

Guest


@Chaidhanan
จริงฯแล้วไม่มีอะไรเลยครับท่าน ไอ้เด็กห่าพวกนี้คิดอะไรไม่เป็น
เป็นกระผม ผมไม่มาเสียเวลาทำให้เป็น Excel/etc...

เป็นเด็กแต่หัวสมองเป็นคนแก่วัย ห่าลากพวกนี้


ปล. ด่าเล่นไปอย่างนั้นแหละ ไม่ได้จริงจังอะไร
แสดงความคิดเห็นโดยอ้างถึง ความคิดเห็นนี้
Date : 2020-03-14 13:44:16 By : หน้าฮี
 

   

ค้นหาข้อมูล


   
 

แสดงความคิดเห็น
Re : ปัญหาการ Download excel file จากการ generate โดยใช้ EPPLUS บน C# ASP.NET .NET FrameWork 4.6.1
 
 
รายละเอียด
 
ตัวหนา ตัวเอียง ตัวขีดเส้นใต้ ตัวมีขีดกลาง| ตัวเรืองแสง ตัวมีเงา ตัวอักษรวิ่ง| จัดย่อหน้าอิสระ จัดย่อหน้าชิดซ้าย จัดย่อหน้ากึ่งกลาง จัดย่อหน้าชิดขวา| เส้นขวาง| ขนาดตัวอักษร แบบตัวอักษร
ใส่แฟลช ใส่รูป ใส่ไฮเปอร์ลิ้งค์ ใส่อีเมล์ ใส่ลิ้งค์ FTP| ใส่แถวของตาราง ใส่คอลัมน์ตาราง| ตัวยก ตัวห้อย ตัวพิมพ์ดีด| ใส่โค้ด ใส่การอ้างถึงคำพูด| ใส่ลีสต์
smiley for :lol: smiley for :ken: smiley for :D smiley for :) smiley for ;) smiley for :eek: smiley for :geek: smiley for :roll: smiley for :erm: smiley for :cool: smiley for :blank: smiley for :idea: smiley for :ehh: smiley for :aargh: smiley for :evil:
Insert PHP Code
Insert ASP Code
Insert VB.NET Code Insert C#.NET Code Insert JavaScript Code Insert C#.NET Code
Insert Java Code
Insert Android Code
Insert Objective-C Code
Insert XML Code
Insert SQL Code
Insert Code
เพื่อความเรียบร้อยของข้อความ ควรจัดรูปแบบให้พอดีกับขนาดของหน้าจอ เพื่อง่ายต่อการอ่านและสบายตา และตรวจสอบภาษาไทยให้ถูกต้อง

อัพโหลดแทรกรูปภาพ

Notice

เพื่อความปลอดภัยของเว็บบอร์ด ไม่อนุญาติให้แทรก แท็ก [img]....[/img] โดยการอัพโหลดไฟล์รูปจากที่อื่น เช่นเว็บไซต์ ฟรีอัพโหลดต่าง ๆ
อัพโหลดแทรกรูปภาพ ให้ใช้บริการอัพโหลดไฟล์ของไทยครีเอท และตัดรูปภาพให้พอดีกับสกรีน เพื่อความโหลดเร็วและไฟล์ไม่ถูกลบทิ้ง

   
  เพื่อความปลอดภัยและการตรวจสอบ กระทู้ที่แทรกไฟล์อัพโหลดไฟล์จากที่อื่น อาจจะถูกลบทิ้ง
 
โดย
อีเมล์
บวกค่าให้ถูก
<= ตัวเลขฮินดูอารบิก เช่น 123 (หรือล็อกอินเข้าระบบสมาชิกเพื่อไม่ต้องกรอก)







Exchange: นำเข้าสินค้าจากจีน, Taobao, เฟอร์นิเจอร์, ของพรีเมี่ยม, ร่ม, ปากกา, power bank, แฟลชไดร์ฟ, กระบอกน้ำ

Load balance : Server 01
ThaiCreate.Com Logo
© www.ThaiCreate.Com. 2003-2024 All Rights Reserved.
ไทยครีเอทบริการ จัดทำดูแลแก้ไข Web Application ทุกรูปแบบ (PHP, .Net Application, VB.Net, C#)
[Conditions Privacy Statement] ติดต่อโฆษณา 081-987-6107 อัตราราคา คลิกที่นี่