Chủ Nhật

Hiển thị File Excel trong ASP.NET sử dụng C Sharp

Mục đích của bài viết này là làm thế nào để hiển thị chính xác giá trị hay nội dung của các Sheet, cả lời chú thích trong một trang aspx. Điều này có thể rất có ích cho người phát triển muốn làm về tự động trong MS Office.
Chương trình gồm có 2 Panel, 1 Panel chứa các thành phần điều khiển, Panel còn lại là nơi thể hiện nội dung của file Excel.
Zensoft Website - Display Excel Sheet and Chart in a Aspx pages Using C#.
Ta thấy quy trình tương đối đơn giản: Chọn File cần xem -> tách File thành các Sheet -> hiển thị các Sheet đó lên.
 Trước hết, ta xử lý sự kiện click cho List button:
protected static string m_strFileName = "";

protected void btnAvailableShtAndChrt_Click(object sender, EventArgs e)
    {
      
        m_strFileName = txtfileValue.PostedFile.FileName;
        if (m_strFileName == "")
        {
            lblErrText.Text = "File không Tồn tại";
        }
        else
        {
            string strTemp = m_strFileName.Substring(m_strFileName.Length - 3);
            strTemp = strTemp.ToUpper();
            if (strTemp == "XLS")
            {
                drpShtAndChrt.Items.Clear();
                GetListofSheetsAndCharts(m_strFileName, true, drpShtAndChrt);
            }
            else
            {
                lblErrText.Text = "File được chọn không đúng định dạng yêu cầu";
            }
        }
       
    }

Trong hàm này, ta xây dựng Hàm  GetListofSheetsAndCharts(m_strFileName, true, drpShtAndChrt) để tách File thành các Sheet và Chart, có nội dung như sau:
public void GetListofSheetsAndCharts(string strFileName, bool bReadOnly, DropDownList drpList)     {          Excel.Workbook workbook = null;         try         {              if (!bReadOnly)             {                 // mở chế độ Write.                 workbook = appOP.Workbooks.Open(strFileName, 2, false, 5, "", "", true, Excel.XlPlatform.xlWindows, "\t", false, true, 0, true, 1, 0);                          }             else             {                 // Mở chế độ Read                 workbook = appOP.Workbooks.Open(strFileName, 2, true, 5, "", "", true, Excel.XlPlatform.xlWindows, "\t", false, true, 0, true, 1, 0);                          }              // Đọc File Excel.              object SheetRChart = null;             int nTotalWorkSheets = workbook.Sheets.Count;             int nIndex = 0;             for (int nWorkSheet = 1; nWorkSheet <= nTotalWorkSheets; nWorkSheet++)             {                 SheetRChart = workbook.Sheets[(object)nWorkSheet];                 if (SheetRChart is Excel.Worksheet)                 {                     ListItem lstItemAdd = new ListItem(((Excel.Worksheet)SheetRChart).Name + "*WorkSheet", nIndex.ToString(), true);                     drpList.Items.Add(lstItemAdd);                     lstItemAdd = null;                     nIndex++;                 }                 else if (SheetRChart is Excel.Chart)                 {                     ListItem lstItemAdd = new ListItem(((Excel.Chart)SheetRChart).Name + "*Chart", nIndex.ToString(), true);                     drpList.Items.Add(lstItemAdd);                     lstItemAdd = null;                     nIndex++;                 }             }              if (workbook != null)             {                 if (!bReadOnly)                 {                     // Đóng chế độ Write                     workbook.Save();                     workbook = null;                 }                 else                 {                     // Đóng chế độ Read                     workbook.Close(false, false, Type.Missing);                     workbook = null;                 }             }          }         catch (Exception expFile)         {             Response.Write(expFile.ToString());         }         finally         {             if (workbook != null)             {                 if (!bReadOnly)                 {                     // Đóng chế độ Write                     workbook.Save();                     workbook = null;                 }                 else                 {                     // Đóng chế độ Read                     workbook.Close(false, false, Type.Missing);                     workbook = null;                 }             }         }     }

Ta để ý thấy hàm này có 3 tham số truyền vào: Tên File, Chế độ mở File và tên của DropDownList.
Sau khi ta đã thực hiện xong  bước tách File Excel thành các Sheet và chart, ta chỉ cần lựa chọn các Sheet hoặc các Chart để hiển thị lên. Ta xử lý sự kiện click nút Display:
protected void btnDisplay_Click(object sender, EventArgs e)
    {

        if (drpShtAndChrt.SelectedIndex != -1)
        {
            string strSheetorChartName = drpShtAndChrt.SelectedItem.Text;
            // Ta phải xóa bỏ các ký tự "*" vì tên của các Sheet trong Excel không cho phép có kí tự này.
            char[] delimiterChars = { '*' };
            string[] strTemp = strSheetorChartName.Split(delimiterChars);

            if (strTemp[1] == "WorkSheet")
            {
                DisplayExcelSheet(m_strFileName, strTemp[0], true, lblErrText);
            }
            else if (strTemp[1] == "Chart")
            {
                DisplayExcelSheet(m_strFileName, strTemp[0], true, lblErrText, true);
            }
        }

    }
Ở trong hàm này ta phải kiểm tra xem ta lựa chọn File để hiển thị là Sheet hay là Chart. Ta dùng kỹ thuật Overloadding cho hàm DisplayExcelSheet() để thực hiện. Nếu là Sheet thì ta gọi hàm DisplayExcelSheet(m_strFileName, strTemp[0], true, lblErrText) với 4 tham số kèm theo. Còn ngược lại, nếu là Chart thì ta phải gọi hàm có 5 tham số.
public bool DisplayExcelSheet(string strFileName, string strSheetRChartName, bool bReadOnly, Label lblErrorText)
    {
        return DisplayExcelSheet(strFileName, strSheetRChartName, bReadOnly, lblErrText, false);
    }

public bool DisplayExcelSheet(string strFileName, string strSheetRChartName, bool bReadOnly, Label lblErrorText, bool bIsChart)
    {

        appOP.DisplayAlerts = false;
        Excel.Workbook workbook = null;
        Excel.Worksheet worksheet = null;
        Excel.Chart chart = null;

        try
        {

            if (!bReadOnly)
            {
                // Mở chế độ Write.
                workbook = appOP.Workbooks.Open(strFileName, 2, false, 5, "", "", true, Excel.XlPlatform.xlWindows, "\t", false, true, 0, true, 1, 0);
               
            }
            else
            {
                // Mở chế độ Read.
                workbook = appOP.Workbooks.Open(strFileName, 2, true, 5, "", "", true, Excel.XlPlatform.xlWindows, "\t", false, true, 0, true, 1, 0);

            }

            // Đọc File Excel.

            if (bIsChart)
            {
                chart = (Excel.Chart)workbook.Charts[strSheetRChartName];
            }
            else
            {
                worksheet = (Excel.Worksheet)workbook.Sheets[strSheetRChartName];
            }

            // Đọc các mã thông tin của File.
            if (bIsChart)
            {
                if (chart == null)
                {
                    lblErrorText.Text = strSheetRChartName + " Ký tự không được chấp nhận ";
                }
                else
                {
                    ExcelChartRead(chart, this.pnlBottPane);
                }
            }
            else
            {
                if (worksheet == null)
                {
                    lblErrorText.Text = strSheetRChartName + " Sheet sẵn có";
                }
                else
                {
                    this.pnlBottPane.Controls.Add(ExcelSheetRead(worksheet, lblErrText));
                }
            }
           
            if (!bReadOnly)
            {
                // Đóng chế độ Write.
                workbook.Save();
                workbook = null;
            }
            else
            {
                // Đóng chế độ Read.
                workbook.Close(false, false, Type.Missing);
                workbook = null;
            }
        }
        catch (Exception expInterop)
        {
            lblErrText.Text = expInterop.ToString();
            return false;
        }
        finally
        {
            if (workbook != null)
            {
                if (!bReadOnly)
                {
                    // Đóng chế độ Write.
                    workbook.Save();
                    workbook = null;
                }
                else
                {
                    // Đóng chế độ Read.
                    workbook.Close(false, false, Type.Missing);
                    workbook = null;
                }
            }
            appOP.DisplayAlerts = true;
        }
        return true;
    }
Đối với Sheet ta gọi hàm ExcelSheetRead(worksheet, lblErrText). Hàm này có giá trị trả về là một Table Control. Còn với Chart ta thực hiện hàm ExcelChartRead(chart, this.pnlBottPane). Hàm này trả về giá trị Boolean. Trước khi đi chi tiết về 2 hàm này, chúng ta sẽ nói về những Hàm quan trọng trong việc chuyển đổi định dạng từ Excel sang Dot Net.
Thuộc tính đầu tiên đề cập đến là Màu sắc (Color). Hàm ConvertExcelColor2DotNetColor(object objExcelColor) dùng để chuyển đổi màu sắc trong Excel sang Dot Net. Giá trị trả về là một đối tượng Color: 
private System.Drawing.Color ConvertExcelColor2DotNetColor(object objExcelColor)
    {

        string strColor = "";
        uint uColor = 0;
        int nRed = 0;
        int nGreen = 0;
        int nBlue = 0;

        strColor = objExcelColor.ToString();
        uColor = checked((uint)Convert.ToUInt32(strColor));
        strColor = String.Format("{0:x2}", uColor);
        strColor = "000000" + strColor;
        strColor = strColor.Substring((strColor.Length - 6), 6);

        uColor = 0;
        uColor = Convert.ToUInt32(strColor.Substring(4, 2), 16);
        nRed = (int)uColor;

        uColor = 0;
        uColor = Convert.ToUInt32(strColor.Substring(2, 2), 16);
        nGreen = (int)uColor;

        uColor = 0;
        uColor = Convert.ToUInt32(strColor.Substring(0, 2), 16);
        nBlue = (int)uColor;

        return System.Drawing.Color.FromArgb(nRed, nGreen, nBlue);
    }
2 Hàm nữa dùng để chuyển định dạng ngang và dọc của Excel sang Dot Net:
private HorizontalAlign ExcelHAlign2DotNetHAlign(object objExcelAlign)
    {
        switch (((Excel.Range)objExcelAlign).HorizontalAlignment.ToString())
        {
            case "-4131":
                return HorizontalAlign.Left;
            case "-4108":
                return HorizontalAlign.Center;
            case "-4152":
                return HorizontalAlign.Right;
            default:
                return HorizontalAlign.Left;
        }
    }

đó là hàm chuyển đổi giá trị Chiều ngang. Còn hàm sau dùng để chuyển đổi giá trị chiều dọc:
private VerticalAlign ExcelVAlign2DotNetVAlign(object objExcelAlign)
    {
        switch (((Excel.Range)objExcelAlign).VerticalAlignment.ToString())
        {
            case "-4160":
                return VerticalAlign.Top;
            case "-4108":
                return VerticalAlign.Middle;
            case "-4107":
                return VerticalAlign.Bottom;
            default:
                return VerticalAlign.Bottom;
        }

    }

 Đó là 3 Hàm rất quan trọng trong việc chuyển đổi các thuộc tính từ Excel sang Dot Net. Bây giờ ta quay lại 2 hàm hiển thị Chart và Sheet ở bên trên.
Trước tiên là Hàm ExcelChartRead(Excel.Chart objExcelChart, Panel ctrlCollPane) hiển thị một Chart:
public bool ExcelChartRead(Excel.Chart objExcelChart, Panel ctrlCollPane)
    {

        Image imgChart = null;
        try
        {
            objExcelChart.Export(@"C:\TempGif.gif", "GIF", true);
            imgChart = new Image();
            imgChart.ImageUrl = @"C:\TempGif.gif";
            ctrlCollPane.Controls.Add(imgChart);
            imgChart.Dispose();
        }
        catch (Exception expFileError)
        {
            Response.Write(expFileError.ToString());
            return false;
        }
        finally
        {
            if (imgChart != null)
            {
                imgChart.Dispose();
            }
        }
        return true;
    }
còn đây là hàm ExcelSheetRead(Excel.Worksheet objExcelSheet, Label lblErrText) thể hiện một Sheet: 
public Control ExcelSheetRead(Excel.Worksheet objExcelSheet, Label lblErrText)
    {

        int nMaxCol = ((Excel.Range)objExcelSheet.UsedRange).EntireColumn.Count;
        int nMaxRow = ((Excel.Range)objExcelSheet.UsedRange).EntireRow.Count;
  

        Table tblOutput = new Table();
       
        TableRow TRow = null;
        TableCell TCell = null;

        string strSize = "";
        int nSizeVal = 0;
        bool bMergeCells = false;
        int nMergeCellCount = 0;
        int nWidth = 0;

      
        if (objExcelSheet == null)
        {
            return (Control)tblOutput;
        }
       
        tblOutput.CellPadding = 0;
        tblOutput.CellSpacing = 0;
        tblOutput.GridLines = GridLines.Both;


        try
        {

            for (int nRowIndex = 1; nRowIndex <= nMaxRow; nRowIndex++)
            {
                TRow = null;
                TRow = new TableRow();


                for (int nColIndex = 1; nColIndex <= nMaxCol; nColIndex++)
                {

                    TCell = null;
                    TCell = new TableCell();
                    if (((Excel.Range)objExcelSheet.Cells[nRowIndex, nColIndex]).Value2 != null)
                    {

                        TCell.Text = ((Excel.Range)objExcelSheet.Cells[nRowIndex, nColIndex]).Text.ToString();
                        if (((Excel.Range)objExcelSheet.Cells[nRowIndex, nColIndex]).Comment != null)
                        {
                            TCell.ForeColor = System.Drawing.Color.Blue;
                            TCell.ToolTip = ((Excel.Range)objExcelSheet.Cells[nRowIndex, nColIndex]).Comment.Shape.AlternativeText;
                        }
                        else
                        {
                            TCell.ForeColor = ConvertExcelColor2DotNetColor(((Excel.Range)objExcelSheet.Cells[nRowIndex, nColIndex]).Font.Color);
                        }

                        TCell.BorderWidth = 2;
                        TCell.Width = 140; //TCell.Width = 40;

                        //*
                        TCell.Font.Bold = (bool)((Excel.Range)objExcelSheet.Cells[nRowIndex, nColIndex]).Font.Bold;
                        TCell.Font.Italic = (bool)((Excel.Range)objExcelSheet.Cells[nRowIndex, nColIndex]).Font.Italic;
                        strSize = ((Excel.Range)objExcelSheet.Cells[nRowIndex, nColIndex]).Font.Size.ToString();
                        nSizeVal = Convert.ToInt32(strSize);
                        TCell.Font.Size = FontUnit.Point(nSizeVal);
                        TCell.BackColor = ConvertExcelColor2DotNetColor(((Excel.Range)objExcelSheet.Cells[nRowIndex, nColIndex]).Interior.Color);

                        if ((bool)((Excel.Range)objExcelSheet.Cells[nRowIndex, nColIndex]).MergeCells != false)
                        {
                            if (bMergeCells == false)
                            {
                                TCell.ColumnSpan = (int)((Excel.Range)objExcelSheet.Cells[nRowIndex, nColIndex]).MergeArea.Columns.Count;
                                nMergeCellCount = (int)((Excel.Range)objExcelSheet.Cells[nRowIndex, nColIndex]).MergeArea.Columns.Count;
                                nMergeCellCount--;
                                bMergeCells = true;
                            }
                            else if (nMergeCellCount == 0)
                            {
                                TCell.ColumnSpan = (int)((Excel.Range)objExcelSheet.Cells[nRowIndex, nColIndex]).MergeArea.Columns.Count;
                                nMergeCellCount = (int)((Excel.Range)objExcelSheet.Cells[nRowIndex, nColIndex]).MergeArea.Columns.Count;
                                nMergeCellCount--;
                            }
                        }
                        else
                        {
                            bMergeCells = false;
                        }

                        TCell.HorizontalAlign = ExcelHAlign2DotNetHAlign(((Excel.Range)objExcelSheet.Cells[nRowIndex, nColIndex]));
                        TCell.VerticalAlign = ExcelVAlign2DotNetVAlign(((Excel.Range)objExcelSheet.Cells[nRowIndex, nColIndex]));
                        TCell.Height = Unit.Point(Decimal.ToInt32(Decimal.Parse((((Excel.Range)objExcelSheet.Cells[nRowIndex, nColIndex]).RowHeight.ToString()))));
                        nWidth = Decimal.ToInt32(Decimal.Parse((((Excel.Range)objExcelSheet.Cells[nRowIndex, nColIndex]).ColumnWidth.ToString())));
                        TCell.Width = Unit.Point(nWidth * nWidth);
                        //*/

                    }
                    else
                    {
                        if ((bool)((Excel.Range)objExcelSheet.Cells[nRowIndex, nColIndex]).MergeCells == false)
                        {
                            bMergeCells = false;
                        }
                        if (bMergeCells == true)
                        {
                            nMergeCellCount--;
                            continue;
                        }
                        TCell.Text = "&nbsp;";
                        if (((Excel.Range)objExcelSheet.Cells[nRowIndex, nColIndex]).Comment != null)
                        {
                            TCell.ForeColor = System.Drawing.Color.Blue;
                            TCell.ToolTip = ((Excel.Range)objExcelSheet.Cells[nRowIndex, nColIndex]).Comment.Shape.AlternativeText;
                        }
                        else
                        {
                            TCell.ForeColor = ConvertExcelColor2DotNetColor(((Excel.Range)objExcelSheet.Cells[nRowIndex, nColIndex]).Font.Color);
                        }
                        TCell.Font.Bold = (bool)((Excel.Range)objExcelSheet.Cells[nRowIndex, nColIndex]).Font.Bold;
                        TCell.Font.Italic = (bool)((Excel.Range)objExcelSheet.Cells[nRowIndex, nColIndex]).Font.Italic;
                        strSize = ((Excel.Range)objExcelSheet.Cells[nRowIndex, nColIndex]).Font.Size.ToString();
                        nSizeVal = Convert.ToInt32(strSize);
                        TCell.Font.Size = FontUnit.Point(nSizeVal);
                        TCell.BackColor = ConvertExcelColor2DotNetColor(((Excel.Range)objExcelSheet.Cells[nRowIndex, nColIndex]).Interior.Color);

                        TCell.Height = Unit.Point(Decimal.ToInt32(Decimal.Parse((((Excel.Range)objExcelSheet.Cells[nRowIndex, nColIndex]).RowHeight.ToString()))));
                        nWidth = Decimal.ToInt32(Decimal.Parse((((Excel.Range)objExcelSheet.Cells[nRowIndex, nColIndex]).ColumnWidth.ToString())));
                        TCell.Width = Unit.Point(nWidth * nWidth);
                    }

                    //TCell.BorderStyle = BorderStyle.Solid;
                    //TCell.BorderWidth = Unit.Point(1);
                    //TCell.BorderColor = System.Drawing.Color.Gray;

                    TRow.Cells.Add(TCell);


                }

                tblOutput.Rows.Add(TRow);

            }
        }
        catch (Exception ex)
        {
            lblErrText.Text = ex.ToString();
        }
        return (Control)tblOutput;
    }
trên đây, chúng ta mới chỉ thể hiện được File Excel trong C Sharp. Hy vọng các bạn sẽ phát triển nâng cao lên, sao cho chương trình có thể đọc được tất cả các thể loại của MS Office.
Bạn có thể Download toàn bộ mã nguồn của chương trình tại đây.

Nguồn: sttyit

Thứ Sáu

Có các định dạng tùy chỉnh sau đây: y (năm), M (tháng), d (ngày), h (giờ 12), H (giờ 24), m(phút), s (thứ hai), f (phần nhỏ của giây), F (phần nhỏ của giây, không bao gồm số 0 sau cùng), t (PM hoặc AM) và z (múi giờ).
Những ví dụ sau minh họa cụ thể giá trị đầu ra của các kiểu định dạng.
/Khởi tạo thời gian date time 2008-03-09 16:05:07.123
DateTime dt = new DateTime(2008, 3, 9, 16, 5, 7, 123);

String.Format("{0:y yy yyy yyyy}", dt);  // "8 08 008 2008"   năm
String.Format("{0:M MM MMM MMMM}", dt);  // "3 03 Mar March"  tháng
String.Format("{0:d dd ddd dddd}", dt);  // "9 09 Sun Sunday" ngày
String.Format("{0:h hh H HH}",     dt);  // "4 04 16 16"      giờ 12/24
String.Format("{0:m mm}",          dt);  // "5 05"            phút
String.Format("{0:s ss}",          dt);  // "7 07"            giây
String.Format("{0:f ff fff ffff}", dt);  // "1 12 123 1230"   phần nhỏ của giây
String.Format("{0:F FF FFF FFFF}", dt);  // "1 12 123 123"    phần nhỏ của giây (không có số 0)
String.Format("{0:t tt}",          dt);  // "P PM"            A.M. or P.M.
String.Format("{0:z zz zzz}",      dt);  // "-6 -06 -06:00"   muối giờ
 Sử dụng dấu phân cách”/” , “:”. Các ký tư này sẻ được chèn vào kết quả đầu ra, để xác đinh thời gian.

//Dấu phân cách trong định dạng của người Đức là "." (chuyển "/" =>".")
String.Format("{0:d/M/yyyy HH:mm:ss}", dt);// "9/3/2008 16:05:07" - english (en-US)
String.Format("{0:d/M/yyyy HH:mm:ss}", dt);// "9.3.2008 16:05:07" - german (de-DE)

//Dưới đây là một vài ví dụ về tùy chỉnh định dạng kiểu DateTime
//Định dạng tháng/ngày/năm với ký tự "0" và không có ký tự "0"
String.Format("{0:M/d/yyyy}", dt);            // "3/9/2008"
String.Format("{0:MM/dd/yyyy}", dt);          // "03/09/2008"

//Lấy tên của ngày/tháng
String.Format("{0:ddd, MMM d, yyyy}", dt);    // "Sun, Mar 9, 2008"
String.Format("{0:dddd, MMMM d, yyyy}", dt);  // "Sunday, March 9, 2008"

//Lấy năm với 2, 4 ký tự
String.Format("{0:MM/dd/yy}", dt);            // "03/09/08"
String.Format("{0:MM/dd/yyyy}", dt); // "03/09/2008"

Định dạng Datetime với các kiểu mẫu được định sẳn.
Trong DateTimeFormatInfo có các kiểu mẫu định sẳn cho các culture hiện hành. Ví dụ ShortTimePattern định dạng h:mm tt cho en-US culture và định dạng HH:mm cho de-DEculture.
Bảng sau cho thấy các kiểu mẫu định sẳn trong DateTimeFormatInfo đươc định theo en-US culture. Cột đầu tiên chỉ ra các kiểu mẫu được định sẳn.
Kiểu mẫu DateTimeFormatInfo Giá trị định sẳn (en-US culture)
tShortTimePatternh:mm tt
dShortDatePatternM/d/yyyy
TLongTimePatternh:mm:ss tt
DLongDatePatterndddd, MMMM dd, yyyy
f
(combination of D and t)
dddd, MMMM dd, yyyy h:mm tt
FFullDateTimePatterndddd, MMMM dd, yyyy h:mm:ss tt
g(combination of d and t)M/d/yyyy h:mm tt
G(combination of d and T)M/d/yyyy h:mm:ss tt
m,MMonthDayPatternMMMM dd
y,YYearMonthPatternMMMM, yyyy
r,RRFC1123Patternddd, dd MMM yyyy HH':'mm':'ss 'GMT' (*)
sSortableDateTi­mePatternyyyy'-'MM'-'dd'T'HH':'mm':'ss (*)
uUniversalSorta­bleDateTimePat­ternyyyy'-'MM'-'dd HH':'mm':'ss'Z'(*)
  (*) = không phụ thuộc vào culture
Ví dụ sau minh họa cách sử dụng kiểu mẫu định sẳn.
String.Format("{0:t}", dt);  // "4:05 PM"                         ShortTime
String.Format("{0:d}", dt);  // "3/9/2008"                        ShortDate
String.Format("{0:T}", dt);  // "4:05:07 PM"                      LongTime
String.Format("{0:D}", dt);  // "Sunday, March 09, 2008"          LongDate
String.Format("{0:f}", dt);//"Sunday, March 09, 2008 4:05 PM"  LongDate+ShortTime
String.Format("{0:F}", dt);//"Sunday, March 09, 2008 4:05:07 PM" FullDateTime
String.Format("{0:g}", dt);//"3/9/2008 4:05 PM"                ShortDate+ShortTime
String.Format("{0:G}", dt);//"3/9/2008 4:05:07 PM"             ShortDate+LongTime
String.Format("{0:m}", dt);  // "March 09"                        MonthDay
String.Format("{0:y}", dt);  // "March, 2008"                     YearMonth
String.Format("{0:r}", dt);  // "Sun, 09 Mar 2008 16:05:07 GMT"   RFC1123
String.Format("{0:s}", dt);  // "2008-03-09T16:05:07"             SortableDateTime
String.Format("{0:u}", dt);  // "2008-03-09 16:05:07Z"            UniversalSortabl
stty

Thứ Hai

Hàm tạo mã ngẫu nhiên

Hàm tạo mã ngẫu nhiên chỉ gồm chữ số, cả số cả ký tự ...
Hàm sau đây sẽ tạo mã ngẫu nhiên chỉ gồm các chữ số
public string MaNgauNhien_So(int codeCount)
{
    string allChar = "0,1,2,3,4,5,6,7,8,9";
    string[] allCharArray = allChar.Split(',');
    string randomCode = "";
    int temp = -1;

    Random rand = new Random();
    for (int i = 0; i < codeCount; i++)
    {
        if (temp != -1)
        {
            rand = new Random(i * temp * ((int)DateTime.Now.Ticks));
        }
        int t = rand.Next(10);
        if (temp != -1 && temp == t)
        {
            return MaNgauNhien_So(codeCount);
        }
        temp = t;
        randomCode += allCharArray[t];
    }
    return randomCode;
}
 Hàm sau đây sẽ tạo chuỗi ngẩu nhiên có cả số và ký tự
public string MaNgauNhien_SoChu(int codeCount)
{
    string allChar = "0,1,2,3,4,5,6,7,8,9
 ,a,b,c,d,e,f,g,h,i,j,k,l,m,n,o,p,q,r,s,t,u,v,w,x,y,z";
    string[] allCharArray = allChar.Split(',');
    string randomCode = "";
    int temp = -1;

    Random rand = new Random();
    for (int i = 0; i < codeCount; i++)
    {
        if (temp != -1)
        {
            rand = new Random(i * temp * ((int)DateTime.Now.Ticks));
        }
        int t = rand.Next(36);
        if (temp != -1 && temp == t)
        {
            return MaNgauNhien_SoChu(codeCount);
        }
        temp = t;
        randomCode += allCharArray[t];
    }
    return randomCode;
}
hmweb

 
Design by Free WordPress Themes | Bloggerized by Lasantha - Premium Blogger Themes | Blogger Templates