namespace WinFormExcel
{
static class ExtensionMethod
{
/// <summary>
/// 根据视图获取自动编号。
/// </summary>
/// <param name="dataView"></param>
/// <param name="letters"></param>
/// <returns></returns>
#region
public static string GetNewID(this DataView dataView, string letters)
{
dataView.RowFilter = null; // 清除该筛选器。
dataView.RowStateFilter = DataViewRowState.CurrentRows; // 包括未更改行、新行和已修改行的当前行。
var query = from item in dataView.Cast<DataRowView>()
let ID = item.Row.Field<string>(0).Substring(letters.Length)
select ID;
int id = query.Any() ? int.Parse(query.Max()) + 1 : 1;
return string.Format("{0}{1:D5}", letters, id); // D5 <=> 00000
}
#endregion
/// <summary>
/// 将 TextBoxBase,ListControl,DateTimePicker 控件的 Text 属性重置为其默认值。
/// </summary>
/// <param name="group"></param>
#region
public static void ClearText(this GroupBox group)
{
foreach (Control ctrl in group.Controls)
{
if (ctrl is TextBoxBase || ctrl is ListControl || ctrl is DateTimePicker)
ctrl.ResetText();
}
}
#endregion
/// <summary>
/// 用 DataGridView 控件内容导出 Excel 报表。
/// </summary>
/// <param name="gridView"></param>
/// <param name="caption"></param>
#region
public static void PrintToExcel(this DataGridView gridView, string caption)
{
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;
book.Password = "jinzhexian";
sheet.Name = caption; // 工作表名。
Excel.Range range = sheet.get_Range("B1", Type.Missing).get_Resize(2, gridView.ColumnCount);
range.MergeCells = true; // 合并单元格。
range.Font.Size = 16;
range.HorizontalAlignment = Excel.XlHAlign.xlHAlignCenter; // 文本水平居中。
range.Value2 = caption; // 表标题。
range = range.get_Offset(1, 0).get_Resize(1, gridView.ColumnCount);
range.HorizontalAlignment = Excel.XlHAlign.xlHAlignCenter; // 文本水平居中。
range.Value2 = gridView.Columns.Cast<DataGridViewColumn>().Select(sm => sm.HeaderText).ToArray(); // 列标题。
foreach (DataGridViewRow row in gridView.Rows)
{
range = range.get_Offset(1, 0);
range.Value2 = row.Cells.Cast<DataGridViewCell>().Select(sm => sm.FormattedValue).ToArray();
}
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
}
}