[.NET] DevExpress เมื่อ Export ข้อมูลใน Grid มาเป็นไฟล์ Excel คอมม่า ( , ) หาย และไม่แสดงเป็นตัวเลข

สำหรับปัญหานี้เป็นปัญหาที่ท้าทาย และหาข้อสาเหตุของปัญหายากมากครับ เนื่องจากที่บริษัทได้ Upgrade ตัว DevExpress แบบก้าวกระโดดครับ

  • ของเดิมเวอร์ชัน 13.1
  • ชองใหม่เวอร์ชัน 20.2

ห่างกันตั้ง 7 เวอร์ชัน นอกจาก API ที่ถูกยกเลิก(Deprecate) แล้ว มันยังมี API ที่เพิ่มเติมเข้ามา ซึ่งมันไม่ได้บอกตอน Compile หรือตัว Tool ที่ Check Comparability ไม่สามารถตรวจสอบได้ครอบคลุมครับจึงเป็นที่มาของปัญหา

เมื่อ Export ข้อมูลใน Grid มาเป็นไฟล์ Excel คอมม่า ( , ) หาย และไม่แสดงเป็นตัวเลข

ปัญหาของเรื่องนี้ T__T
  • ปัญหาที่เกิดหลังใช้ DevExpress 20.2

แนวทางการแก้ไขปัญหา

  • ต้องย้อนอดีตกันก่อนครับ Dev Express 14.2 มันมี Export Engine ใหม่
    • WYSIWYG Export (ของเดิม) : จอแสดงอะไร ให้ในไฟล์ที่ Export ได้แสดงตามในจอได้ก็เพียงพอครับ
    • Data Aware Export (ของใหม่ Dev Express 14.2): เป็น Engine ที่ช่วยให้การ Export ข้อมูลในกลุ่ม Spreadsheet มันฉลาดขึ้นครับ อาทิ เช่น ถ้า Grid มีการ Sum ไว้ ใน Excel มันจะผูกสูตร Sum ให้เลยครับ สุดยอดไปเลยยย
  • เนื่องจาก Feature ใหม่ Data Aware Export ทำให้ตอน Export Excel ต้องมีการ Property เพิ่มสำหรับหน้าจอ Preview ที่ยังเป็น Mode WYSIWYG Export ต้องกำหนดค่า RepositoryItemTextEdit.XlsxFormatString เพิ่มเติมครับ มาดูตัวอย่างการใช้งานได้จาก Code ด้านล่างเลยครับ
public static void FormatGridColumn(GridView pGridView, GridColumn col, FormatType pColumnType, int pFormatCode, int pColumnWidth)
{
    if (pColumnType == FormatType.Numeric)
    {
        RepositoryItemTextEdit textEdit = new RepositoryItemTextEdit();
        col.DisplayFormat.FormatType = DevExpress.Utils.FormatType.Numeric;
        col.AppearanceCell.TextOptions.HAlignment = HorzAlignment.Far;
        if (pFormatCode == FORMAT_PATTERN.CURRENCY_CODE)
        {
			textEdit.XlsxFormatString = "#,##0.00";			//Set Excel Export Format
			col.DisplayFormat.FormatString = "#,##0.00";
			col.DisplayFormat.Format = new NumberFormatter();
			col.DisplayFormat.FormatType = FormatType.Custom;
			col.Width = pColumnWidth > 200 ? pColumnWidth : 200;
		}
		else if (pFormatCode == FORMAT_PATTERN.RATE_CODE)
		{
			textEdit.XlsxFormatString = "#,##0.0000";		//Set Excel Export Format
			col.DisplayFormat.FormatString = "#,##0.0000";
			col.Width = pColumnWidth > 60 ? pColumnWidth : 60;
		}
	}
	else
	{
		//Do some logic 
	}
}

Discover more from naiwaen@DebuggingSoft

Subscribe to get the latest posts to your email.