กรองเอาเฉพาะตัวเลข (digit) จาก string

ใช้ regular expression

using System;
using System.Text.RegularExpressions;

namespace ConsoleApp1
{
    class Program
    {
        static void Main(string[] args)
        {
            try
            {
                string ipString = "(66)123-456-7890 เบอร์มือถือ ";
                string opString = null;
                Console.WriteLine(ipString);

                Regex regex = new Regex(@"[^\d]");
                opString = regex.Replace(ipString, "");
                Console.WriteLine(opString);
            }
            catch (ArgumentException ex)
            {
                Console.WriteLine(ex.Message);
            }
        }
    }
}

จะได้

(66)123-456-7890 เบอร์มือถือ
661234567890

ใช้ C# อ่านไฟล์ CSV

using System;
using System.Linq;
using System.Text;
using System.Text.RegularExpressions;

namespace ConsoleApp1
{
    class Program
    {
        static void Main(string[] args)
        {
            string filename = "test.csv";
            string text = System.IO.File.ReadAllText(filename, Encoding.GetEncoding(874)).Trim();
            string[] rows = text.Split('\n');
            Console.WriteLine(string.Format("There are {0} rows in '{1}'.", rows.Count(), filename));

            Regex CSVParser = new Regex(",(?=(?:[^\"]*\"[^\"]*\")*(?![^\"]*\"))");
            for (int r = 0; r < rows.Count(); r++)
            {
                //string[] cols = rows[r].Split(',');
                string[] cols = CSVParser.Split(rows[r]);

                for (int c = 0; c < cols.Count(); c++)
                {
                    // clean up the fields (remove " and leading spaces)
                    cols[c] = cols[c].TrimStart(' ', '"');
                    cols[c] = cols[c].TrimEnd('"');
                    Console.Write(cols[c]);
                }
                Console.WriteLine();
            }
        }
    }
}

Link

Posted in C#

เปลี่ยน Input Language Programmatically

/// <summary>
/// Changing Current Input Language to a next installed language
/// </summary>
public void ChangeInputLanguage()
{
   // Nothing to do if there is only one Input Language supported:
    if (InputLanguage.InstalledInputLanguages.Count == 1)
       return;
   // Get index of current Input Language
    int currentLang = InputLanguage.InstalledInputLanguages.IndexOf(InputLanguage.CurrentInputLanguage);
   // Calculate next Input Language
    InputLanguage nextLang = ++currentLang == InputLanguage.InstalledInputLanguages.Count ? 
       InputLanguage.InstalledInputLanguages[0] : InputLanguage.InstalledInputLanguages[currentLang];
   // Change current Language to the calculated:
    ChangeInputLanguage(nextLang);
}

/// <summary>
/// Changing current Input Language to a new one passed in the param
/// </summary>
/// <param name="ISOLang">ISO Culture name string code e.g. "en" for English</param>
public void ChangeInputLanguage(string ISOLang)
{
   // Convert ISO Culture name to InputLanguage object. Be aware: if ISO is not supported
    // ArgumentException will be invoked here
    InputLanguage nextLang = InputLanguage.FromCulture(new System.Globalization.CultureInfo(ISOLang));
   ChangeInputLanguage(nextLang);
}

/// <summary>
/// Changing current Input Language to a new one passed in the param
/// </summary>
/// <param name="LangID">Integer Culture code e.g. 1033 for English</param>
public void ChangeInputLanguage(int LangID)
{
   // Convert Integer Culture code to InputLanguage object. Be aware: if Culture code is not supported
    // ArgumentException will be invoked here
    InputLanguage nextLang = InputLanguage.FromCulture(new System.Globalization.CultureInfo(LangID));
   ChangeInputLanguage(nextLang);
}

/// <summary>
/// Changing current Input Language to a new one passed in the param
/// </summary>
/// <param name="InputLang">New Input Language as InputLanguage object</param>
public void ChangeInputLanguage(InputLanguage InputLang)
{
   // Check is this Language really installed. Raise exception to warn if it is not:
    if (InputLanguage.InstalledInputLanguages.IndexOf(InputLang) == -1)
       throw new ArgumentOutOfRangeException();
   // InputLAnguage changes here:
    InputLanguage.CurrentInputLanguage = InputLang;
}
Posted in C#

สร้างไฟล์ Excel ด้วย C#, NPOI และคลาส NpoiExport

https://www.nuget.org/packages/NPOI/

ติดตั้ง

PM> Install-Package NPOI -Version 2.4.1

Program.cs

using NPOI.HSSF.UserModel;
using System;
using System.Data;
using System.IO;

namespace ConsoleApp1
{
    class Program
    {
        static void Main(string[] args)
        {
            HSSFWorkbook workbook = new HSSFWorkbook();
            var sheet1 = workbook.CreateSheet("Sheet1");
            var sheet2 = workbook.CreateSheet("Sheet2");

            DataTable dt = new DataTable();
            dt.Columns.Add("ชื่อ");
            dt.Columns.Add("Email");
            DataRow row1 = dt.NewRow();
            row1["ชื่อ"] = "Jack";
            row1["Email"] = "mr.phaisarn@gmail.com";
            dt.Rows.Add(row1);
            DataRow row2 = dt.NewRow();
            row2["ชื่อ"] = "Example";
            row2["Email"] = "example@gmail.com";
            dt.Rows.Add(row2);

            string fixedWidthColumn = "0-4000,1-4000,2-6000";
            var exporter = new NpoiExport(fixedWidthColumn);
            exporter.ExportDataTableToWorkbook(dt, "Export_Data");
            exporter.ExportDataTableToWorkbook(dt, "Export_Data2");

            string localFullPath = AppDomain.CurrentDomain.BaseDirectory;
            FileStream FileStreamObject = new System.IO.FileStream(localFullPath + @"Export_Excel.xls", FileMode.Create, FileAccess.Write);
            FileStreamObject.Write(exporter.GetBytes(), 0, exporter.GetBytes().Length);
            FileStreamObject.Close();
        }
    }
}
Continue reading

สร้างไฟล์ Excel ด้วย C#

  1. เพิ่ม Reference
  2. สร้างไฟล์ Excel เปล่า
  3. กำหนดข้อความ ตัวหนา และตำแหน่งกึ่งกลาง
  4. การใช้ Array การใส่สูตร การจัดขนาดคอลัมน์
  5. เพิ่ม WorkSheet และจัดลำดับ WorkSheet
  6. โค๊ดทั้งหมด
Continue reading