2009年4月25日 星期六

程式設定EXCEL 格式

private void button1_Click(object sender, EventArgs e)
...{
if (openFileDialog1.ShowDialog() == DialogResult.OK)
...{
Microsoft.Office.Interop.Excel.Application excelApp = new Microsoft.Office.Interop.Excel.Application();
Microsoft.Office.Interop.Excel.Worksheet excelWs;
Microsoft.Office.Interop.Excel.Workbook excelWorkbook = excelApp.Workbooks.Open(openFileDialog1.FileName,
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);

excelWs = (Microsoft.Office.Interop.Excel.Worksheet)excelWorkbook.Worksheets.get_Item(1);//取得第一個sheet

設定小大位置#region 設定小大位置
excelWs.Cells.VerticalAlignment = Microsoft.Office.Interop.Excel.XlVAlign.xlVAlignTop; //垂直調準
excelWs.Cells.HorizontalAlignment = Microsoft.Office.Interop.Excel.XlHAlign.xlHAlignLeft;//水平調準
excelWs.Cells.EntireRow.AutoFit(); //自動調整列高
excelWs.Cells.EntireColumn.AutoFit(); //自動調整欄寬
#endregion

設定顏色#region 設定顏色
excelWs.get_Range("B:B", Type.Missing).Font.Color = 255;
excelWs.get_Range("D:D", Type.Missing).Font.Color = 255;
excelWs.get_Range("E:J", Type.Missing).Font.Color = 255;
#endregion

調整儲存格格式#region 調整儲存格格式
excelWs.get_Range("B:B", Type.Missing).NumberFormatLocal = "@";
excelWs.get_Range("E:F", Type.Missing).NumberFormatLocal = "@";
excelWs.get_Range("I:J", Type.Missing).NumberFormatLocal = "@";
#endregion

ClearCom(excelWs);
excelWorkbook.Close(true, Type.Missing, Type.Missing);

ClearCom(excelWorkbook);
excelApp.Workbooks.Close();
excelApp.Quit();
ClearCom(excelApp);

excelWs = null;
excelWorkbook = null;
excelApp = null;
MessageBox.Show("設定完成");
}
}

static void ClearCom(object o)
...{
try
...{
System.Runtime.InteropServices.Marshal.ReleaseComObject(o);
}
catch ...{ }
finally
...{
o = null;
}
}

沒有留言:

張貼留言