一、產生新的Excel檔案
1.先確定方案總管的參考裡面有「Microsoft.Office.Interop.Excel 」,如果沒有請自行安裝。
2.using Microsoft.Office.Interop.Excel;
3.
//建立Excel物件
Microsoft.Office.Interop.Excel.Application xlapp =
new Microsoft.Office.Interop.Excel.Application();
//顯式檔案
xlapp.Visible = true;
//建立WorkBook物件
Workbook wb = xlapp.Workbooks.Add(XlWBATemplate.xlWBATWorksheet);
//建立WorkSheet物件
Worksheet ws = (Worksheet)wb.Sheets[1];
//指定要控制的藍為範圍
Range rg = ws.get_Range("A:K", System.Type.Missing);
//字型大小
rg.Font.Size = 10;
//字型粗體
rg.Font.Bold = true;
//儲存格設為純文字
rg.NumberFormatLocal = "@";
//背景顏色
rg.Cells.Interior.Color = ColorTranslator.ToOle(Color.FromArgb(255,255,0));
//宣告路徑字串
string sFileWithPath = null;
//宣告開檔對話框的物件
OpenFileDialog OFDialog1 = new OpenFileDialog();
//指定預設開己的路徑為桌面
OFDialog1.InitialDirectory = System.Environment.GetFolderPath(Environment.SpecialFolder.Desktop);
//預設顯式Excel檔案
OFDialog1.Filter = "*.xlsx|*.XLSX|*.xls|*.XLS";
if (OFDialog1.ShowDialog() == DialogResult.OK)
{
sFileWithPath = OFDialog1.FileName;
xlapp.Visible = true;
Workbook wb = xlapp.Workbooks.Open(sFileWithPath, Type.Missing, Type.Missing, Type.Missing, Type.Missing, Type.Missing, Type.Missing, Type.Missing, Type.Missing, Type.Missing, Type.Missing, Type.Missing, Type.Missing, Type.Missing, Type.Missing);
Worksheet ws = (Worksheet)wb.Sheets[1]; //指定第1個Sheet
Range rg = ws.get_Range("L:X", System.Type.Missing); //設定要控制的欄位區間
.......
....
}
三、金額處理
若有一金額為99,999,用字串時需要千分位符號,計算時需拿掉。
String to Double:
string sMoney = "99,9999";
double dMoneyCount = Convert.ToDouble(sMoney.Replace(",",""));
Double to String:
double dMoneyCount = 999999.0;
string sMoney = dMoneyCount.ToString("#,##");