目前分類:C# (11)

瀏覽方式: 標題列表 簡短摘要

ex: 輸入1,27,53,結果為A,A1,B1

public static string ConvertToExcelColumn(int iValue)
{    
    string strReturn = "";
    
    int iQuotient = iValue / 26;//商數
    int iRemainder = iValue % 26;//餘數
    
    if (iRemainder == 0)
    iQuotient--;  // 剛好整除的時候,商數要減一
    
    if (iQuotient > 0)
    strReturn = Convert.ToChar(64 + iQuotient).ToString();//A 65 利用ASCII做轉換
    
    if (iRemainder == 0)
    strReturn += "Z";
    else
    strReturn += Convert.ToChar(64 + iRemainder).ToString();    //A 65 利用ASCII做轉換
    
    return strReturn;
}

felixhuang 發表在 痞客邦 留言(0) 人氣()

using System.Diagnostics;

public void WriteToWindowsEvent(string aSource,string aMessage){

  if(!EventLog.SourceExists(aSource)){
    EventLog.CreateEventSource(aSource,"Project");
  }
  EventLog oLog = new EventLog("Project");
  oLog.Source = aSource;
  oLog.WriteEntry(aMessage ,EventLogEntryType.Error);
 
}

felixhuang 發表在 痞客邦 留言(0) 人氣()

using System.Web.Mail;


MailMessage objMail = new MailMessage();

objMail.From = strMailFrom;
objMail.To = strTo;
objMail.Cc = strCC;
            
objMail.Bcc = strBCC;
objMail.Subject = strSubject;
            
objMail.Body = strBody;
objMail.BodyFormat = MailFormat.Html;

            
SmtpMail.SmtpServer = System.Configuration.ConfigurationSettings.AppSettings["SmtpServer"];
SmtpMail.Send(objMail);

felixhuang 發表在 痞客邦 留言(0) 人氣()

要使用以下的Class,你需要先引用 Microsoft Visual J# .NET Class Library,從引用(Add Reference)中,找到 "vjslib" 並引用它。

using java.io;
using java.util.zip;

public void CompressFile(string ZipFileName,string[] EntryFileName)
{
// Output stream
FileOutputStream fos = new FileOutputStream(ZipFileName);
// Tie to zip stream
ZipOutputStream zos = new ZipOutputStream(fos);
foreach(string strFileInput in EntryFileName)
{
  // Stream with source file
  FileInputStream fis = new FileInputStream(strFileInput);
  // It's our entry in zip
  string strFileNameWithoutPath=strFileInput;
  if(strFileInput.IndexOf(@"\")!=-1) //把路徑去掉,避免壓縮好的檔案包含完整路徑
    strFileNameWithoutPath=strFileInput.Substring(strFileInput.LastIndexOf(@"\")+1);

  ZipEntry ze = new ZipEntry(strFileNameWithoutPath);
  zos.putNextEntry(ze);
  sbyte[] buffer = new sbyte[1024];
  int len;
  // Read and write until done
  while((len = fis.read(buffer)) >= 0)
  {
    zos.write(buffer, 0, len);
  }
  fis.close();
}
 
// Close everything
zos.closeEntry();
zos.close();
fos.close();
}

felixhuang 發表在 痞客邦 留言(0) 人氣()

Excel.Application objExcel_App = new Excel.Application();
Excel.Workbook objExcel_WB = (Excel.Workbook) objExcel_App.Workbooks.Add(Excel.XlWBATemplate.xlWBATWorksheet);
Excel.Worksheet objExcel_WS = objExcel_WB.Worksheets[1] as Excel.Worksheet;
Excel.Range objExcel_RG = null;

try
{
objExcel_WS.Name = "Test Report";

// 設定第一列Excel內容
ArrayList alRow = new ArrayList();
object[] objRow = {"A","B","C","D"};
alRow.Add(objRow);

objExcel_RG = objExcel_WS.get_Range("A1","D1");    
objExcel_RG.GetType().InvokeMember("Value",BindingFlags.SetProperty,null,objExcel_RG,
     alRow.ToArray(typeof(object)) as object[]);


// 設定Excel格式
objExcel_RG.Font.Bold = true;
objExcel_RG.Font.Name = "Arial";
objExcel_RG.Font.Size = 10;

objExcel_RG.Font.Color = 255; //字型顏色
objExcel_RG.Interior.Color =
System.Drawing.ColorTranslator.ToOle(System.Drawing.Color.Yellow); //背景顏色
objExcel_RG.VerticalAlignment = Excel.XlVAlign.xlVAlignTop; //垂直對齊
objExcel_RG.HorizontalAlignment = Excel.XlHAlign.xlHAlignCenter;//水平對齊
objExcel_RG.EntireRow.AutoFit(); //自動調整列高
objExcel_RG.EntireColumn.AutoFit(); //自動調整欄寬

objExcel_WS.get_Range("A1", "B1").Merge(false); //設定A1:B1儲存格合併
objExcel_WS.get_Range("C:C",Type.Missing).NumberFormatLocal
= "@";  //設定C欄儲存格格式為文字
objExcel_WS.get_Range("D:D",Type.Missing).NumberFormatLocal
= "yyyy/MM/dd";  //設定C欄儲存格格式


Array.Clear(objColumnTemp,0,objColumnTemp.Length);              

objExcel_WS.SaveAs(strFilePath,Type.Missing,Type.Missing,Type.Missing
           ,Type.Missing,Type.Missing,Type.Missing
                    ,Type.Missing,Type.Missing);
                    
objExcel_App.Workbooks.Close();

}
catch(Exception exp)
{
    throw exp;
}
finally
{
      objExcel_App.Quit();
      System.Runtime.InteropServices.Marshal.ReleaseComObject(objExcel_RG);
      System.Runtime.InteropServices.Marshal.ReleaseComObject(objExcel_WS);
      System.Runtime.InteropServices.Marshal.ReleaseComObject(objExcel_WB);
      System.Runtime.InteropServices.Marshal.ReleaseComObject(objExcel_App);
      GC.Collect();
}

objExcel_WS.get_Range(pricingUtil.ConvertToExcelColumn(iCol)+":"+pricingUtil.ConvertToExcelColumn(iCol),Type.Missing).NumberFormatLocal = "@";objExcel_WS.get_Range(pricingUtil.ConvertToExcelColumn(iCol)+":"+pricingUtil.ConvertToExcelColumn(iCol),Type.Missing).NumberFormatLocal = "@";

felixhuang 發表在 痞客邦 留言(3) 人氣()

要判斷執行中的程式,最方便的方式是用System.Diagnostics.Process

ex:
using System.Diagnostics;

Process[] process = Process.GetProcessesByName("EXCEL");
if(process.Length > 0){
    Log("Have been working in Background! Please try again later.");
}

但是VS2003用 Process ,在某些系統上會出現奇怪的 Couldn't get process information from remote machine 錯誤,微軟說是BUG,請改用VS2005(媽的),如果你也不幸遇到了,可以改用WMI。

ex:
using System.Management;
ManagementObjectSearcher mo = new ManagementObjectSearcher("SELECT * FROM Win32_Process Where NAME='EXCEL'");
   
if(mo.Get().Count > 0){
    Log("It is calculating.... Please try it later.");
}

WMI也可以列舉所有執行中的程式,以下為範例.

ex:
using System.Management;
ManagementObjectSearcher mo = new ManagementObjectSearcher("SELECT * FROM Win32_Process'");

foreach (ManagementObject obj in mo.Get()) 
    strProgram = obj["Description"].ToString();

felixhuang 發表在 痞客邦 留言(0) 人氣()

程式碼很簡單,要注意引用DTS,一般位置在 C:\Program Files\Microsoft SQL Server\80\Tools\Binn\dtspkg.dll。

   using DTS;
   object pVarPersistStgOfHost = null;
   Package2Class package = new Package2Class();
   package.LoadFromSQLServer(_IP, _DB_USER, _DB_PWD, DTSSQLServerStorageFlags.DTSSQLStgFlag_Default,
    null, null, null, strPackageName, ref pVarPersistStgOfHost);

   try
   {
         package.Execute();
         bDTSflag = true;
   }
   catch(Exception exp)
   {
         throw  exp;
   }
   finally
   {
         package.UnInitialize();
         package = null;    
   }

felixhuang 發表在 痞客邦 留言(0) 人氣()

這篇後來找到MSDN上有,就直接引用它的範例:
DateTime oldDate = new DateTime(2002,7,15);
DateTime newDate = DateTime.Now;
// Difference in days, hours, and minutes.
TimeSpan ts = newDate - oldDate;
// Difference in days.
int differenceInDays = ts.Days;
System.Console.WriteLine("Difference in days: {0} ", differenceInDays);
System.Console.ReadLine();
另外你也可以用 TimeSpan 的 Hours,Minutse,Seconds 來查詢其它時間的差距。
可以適用在.NET所有 ( .NET FRAMWORK 1.0、2.0、3.5) 下

felixhuang 發表在 痞客邦 留言(0) 人氣()

交接來的程式發生了一個轉型上的錯誤,原來用 Convert 取整數時小數會進位,之後使用(int)結果便是正確,所以Convert 跟 (int)的轉型機制不同,使用在浮點運算要小心。 

double d = 105.555;
   int i1 = Convert.ToInt32(d); // = 106
   int i2 = (int)(d);   // = 105

felixhuang 發表在 痞客邦 留言(1) 人氣()

C# 檢查是否為數字

private bool IsNumeric(string InputValue)
  {
   bool Numeric = double.TryParse( InputValue , System.Globalization.NumberStyles.Any , null , out Dummy);
  
   return Numeric;
  }

felixhuang 發表在 痞客邦 留言(1) 人氣()

在.NET 2.0 之後,你可以直接輸出民國的日期格式:

例:
using System.Globalization;

TaiwanCalendar twC = new TaiwanCalendar();                   
string tdate = "民國 " + twC.GetYear(dDate) + "/" + twC.GetMonth(dDate) + "/" + twC.GetDayOfMonth(dDate);

ex: 民國 98/11/20

felixhuang 發表在 痞客邦 留言(1) 人氣()