using System;
using System.Data;
using Excel = Microsoft.Office.Interop.Excel;
// 添加引用 -> .NET -> Microsoft.Office.Interop.Excel(2003->11.0, 2007->12.0)
namespace WinFormTable
{
static class ClassSchema
{
private static DataTable table;
static ClassSchema()
{
table = new DataTable("File");
table.Locale = System.Globalization.CultureInfo.InvariantCulture; // 固定区域。
DataColumn column = table.Columns.Add("Name", typeof(String));
table.Columns.Add("Length", typeof(Decimal));
table.Columns.Add("CreationTime", typeof(DateTime));
table.Constraints.Add("PK", column, true); // 创建主键。
table.DefaultView.ApplyDefaultSort = true; // 使用默认排序。
}
public static DataTable UserTable
{
get { return table; }
}
#region PrintToExcel
public static void PrintToExcel(this DataTable table, string caption, params string[] columns)
{
Excel.Application xls = new Excel.Application();
try
{
Excel.Workbook book = xls.Workbooks.Add(Excel.XlWBATemplate.xlWBATWorksheet);
Excel.Worksheet sheet = book.ActiveSheet as Excel.Worksheet;
xls.Visible = true; // 显示Excel工作薄。
book.Password = "jinzhexian"; // 设置密码。
sheet.Name = caption; // 设置Excel工作表名。
sheet.get_Range("C4", Type.Missing).EntireColumn.NumberFormat = "#,##0.00";
sheet.get_Range("D4", Type.Missing).EntireColumn.NumberFormat = "yyyy-MM-dd HH:mm:ss";
Excel.Range range = sheet.get_Range("B1", Type.Missing).get_Resize(2, table.Columns.Count);
range.MergeCells = true; // 合并单元格。
range.Font.Size = 16; // 设置字体大小。
range.HorizontalAlignment = Excel.XlHAlign.xlHAlignCenter; // 文本水平居中。
range.Value2 = caption; // 设置标题。
range = range.get_Offset(1, 0).get_Resize(1, table.Columns.Count);
range.HorizontalAlignment = Excel.XlHAlign.xlHAlignCenter; // 文本水平居中。
range.Value2 = columns; // 设置列标题。
foreach (DataRow row in table.Rows)
{
range = range.get_Offset(1, 0);
range.Value2 = row.ItemArray;
}
range = range.get_Offset(2, 0);
range.MergeCells = true; // 合并单元格。
range.HorizontalAlignment = Excel.XlHAlign.xlHAlignCenter; // 文本水平居中。
range.Value2 = string.Format("打印日期: {0:yyyy'年'M'月'd'日'}", DateTime.Today);
range.EntireColumn.AutoFit(); // 自动调整列宽。
sheet.get_Range("A4", Type.Missing).Select();
xls.SendKeys("%WFF", true); // 冻结拆分窗格 Microsoft Office 2003(%WF), 2007(%WFF)。
}
catch
{
xls.Quit();
}
finally
{
xls = null;
GC.Collect();
}
}
#endregion
}
}