Winform中读EXCEL表及DataGridView、WebBrowser控件实现打印、打印预览、打...
好久没有写Winform程序,写了一天写得头都晕了。中间有用到读取EXCEL表,DataGridView、WebBrowser、ToolScript、等一系列控件的使用,以及实现了WebBrowser控件实现的单个文件打印和多个文件打印、打印预览、打印设置。其中打印的文档有用到NVelocity模板机制。虽然看起来一小小程序,却也花费了本人不少心思。麻雀虽小,五脏俱全,值得欣慰的是总算圆满完成。下面把各文件贴上来。。。
一、Form1.cs 主操作文件
using System;
using System.Collections.Generic;
using System.ComponentModel;
using System.Data;
using System.Data.OleDb;
using System.Drawing;
using System.Text;
using System.Windows.Forms;
using System.IO;
namespace XlsDataTool
{
public partial class Form1 :Form
{
private string tpl;
public Form1()
{
InitializeComponent();
}
#region 读取EXCEL
/// <summary>
/// 读取Excel文档
/// </summary>
/// <param name="Path">文件名称</param>
/// <returns>返回一个数据集</returns>
///
public static DataTable ExcelToDS(string Path)
{
if (!string.IsNullOrEmpty(Path))
{
string strConn = "Provider=Microsoft.Jet.OLEDB.4.0;" + "Data Source=" + Path + ";" + "Extended Properties=Excel 8.0;";
OleDbConnection conn = new OleDbConnection(strConn);
conn.Open();
string strExcel = "";
OleDbDataAdapter myCommand = null;
DataTable table = null;
strExcel = "select * from [客户资料(1)$]";
myCommand = new OleDbDataAdapter(strExcel, strConn);
table = new DataTable();
myCommand.Fill(table);
return table;
}
return null;
}
#endregion
/// <summary>
/// webBrowser加载完的事件
/// </summary>
/// <param name="sender"></param>
/// <param name="e"></param>
private void webBrowser1_DocumentCompleted(object sender, WebBrowserDocumentCompletedEventArgs e)
{
if (webBrowser1.ReadyState != WebBrowserReadyState.Complete)//判断是否加载完成
return;
}
/// <summary>
/// 打印多项调用的方法
/// </summary>
public void GetDataList()
{
int count = 0;
for(int i = 0;i<XlsDataGridView.Rows.Count;i++)
{
//判断是否是checkbox列
if (this.XlsDataGridView.Columns[0].GetType().Name == "DataGridViewCheckBoxColumn") //判断是否是复选框列
{
if (((DataGridViewCheckBoxCell)XlsDataGridView.Rows[i].Cells[0]).Tag != null && ((DataGridViewCheckBoxCell)XlsDataGridView.Rows[i].Cells[0]).Tag.ToString() == "1")
{
count++;
ReplaceTemplate2(i,1);//替换模板值的方法
}
}
}
if (count == 0)
{
System.Windows.Forms.MessageBox.Show("请选择需要打印的记录!");
}
}
/// <summary>
/// 点击列表事件
/// </summary>
/// <param name="sender"></param>
/// <param name="e"></param>
private void XlsDataGridView_CellMouseClick(object sender, DataGridViewCellMouseEventArgs e)
{
if (e.RowIndex >= 0)
{
ReplaceTemplate2(e.RowIndex, 0);//替换模板值的方法
}
}
/// <summary>
/// 获取html模板文件的html
/// </summary>
/// <param name="path"></param>
/// <returns></returns>
private string GetHtmlCode(string path)
{
using (StreamReader sr = System.IO.File.OpenText(Application.StartupPath + "//" + path))
{
return sr.ReadToEnd();
}
}
/// <summary>
/// //替换模板值
/// </summary>
/// <param name="rowIndex">行索引</param>
private void ReplaceTemplate2(int rowIndex, int flag)
{
NvelocityHelper help = new NvelocityHelper();
help.Init("");
StringHelper objs = new StringHelper();
help.Assign("MyString",objs);
for (int i = 1; i < XlsDataGridView.Rows[rowIndex].Cells.Count; i++)
{
string value = XlsDataGridView.Rows[rowIndex].Cells[i].Value.ToString();
help.Assign(XlsDataGridView.Columns[i].ToolTipText.Trim(), value);
}
webBrowser1.DocumentText = help.Display("temp.htm");
if (flag == 1)
{
webBrowser1.Print();//打印
}
}
/// <summary>
/// 点击单元格内容的事件(用于设置选择和取消复选框列)
/// </summary>
/// <param name="sender"></param>
/// <param name="e"></param>
private void XlsDataGridView_CellContentClick(object sender, DataGridViewCellEventArgs e)
{
if (e.ColumnIndex == 0)//判断是否点击的是第一列
{
if (((DataGridViewCheckBoxCell)XlsDataGridView.Rows[e.RowIndex].Cells[0]).Tag == null)
{
this.XlsDataGridView.Rows[e.RowIndex].Cells[0].Value = true;
((DataGridViewCheckBoxCell)XlsDataGridView.Rows[e.RowIndex].Cells[0]).Tag = 1;
}
else
{
if (((DataGridViewCheckBoxCell)XlsDataGridView.Rows[e.RowIndex].Cells[0]).Tag.ToString() == "0")
{
this.XlsDataGridView.Rows[e.RowIndex].Cells[0].Value = true;
((DataGridViewCheckBoxCell)XlsDataGridView.Rows[e.RowIndex].Cells[0]).Tag = 1;
}
else
{
this.XlsDataGridView.Rows[e.RowIndex].Cells[0].Value = false;
((DataGridViewCheckBoxCell)XlsDataGridView.Rows[e.RowIndex].Cells[0]).Tag = 0;
}
}
}
}
/// <summary>
/// 全选
/// </summary>
/// <param name="sender"></param>
/// <param name="e"></param>
private void toolStripBtnSelectAll_Click(object sender, EventArgs e)
{
//把datagridview的所有记录的第一列的复选框设为选中
for (int i = 0; i < XlsDataGridView.Rows.Count; i++)
{
this.XlsDataGridView.Rows[i].Cells[0].Value = true;
((DataGridViewCheckBoxCell)XlsDataGridView.Rows[i].Cells[0]).Tag = 1;
}
}
/// <summary>
/// 取消
/// </summary>
/// <param name="sender"></param>
/// <param name="e"></param>
private void toolStripBtnSelectCancel_Click(object sender, EventArgs e)
{
//把datagridview的所有记录的第一列的复选框设为选中
for (int i = 0; i < XlsDataGridView.Rows.Count; i++)
{
this.XlsDataGridView.Rows[i].Cells[0].Value = false;
((DataGridViewCheckBoxCell)XlsDataGridView.Rows[i].Cells[0]).Tag = 0;
}
}
/// <summary>
/// 浏览 选择excel文件
/// </summary>
/// <param name="sender"></param>
/// <param name="e"></param>
private void toolStripButton3_Click(object sender, EventArgs e)
{
string mPath = @"F:/XlsDataTool/test.xls";
if (openFileDialog1.ShowDialog() == DialogResult.OK)
{
mPath = openFileDialog1.FileName;
int i = mPath.LastIndexOf(".");
if (mPath.Substring(i).ToLower() != ".xls")
{
System.Windows.Forms.MessageBox.Show("请选择有效的xls文件");
return;
}
//this.textBox1.Text = mPath;
toolStripTextBoxFile.Text = mPath;
}
DataTable table = ExcelToDS(mPath);//@"F:/XlsDataTool/test.xls"调用读取EXCEL文档的方法
if (table != null && table.Rows.Count != 0)
{
XlsDataGridView.AutoGenerateColumns = true;
XlsDataGridView.DataSource = table;//自动绑定DataGridView
}
}
/// <summary>
/// 打印选择项
/// </summary>
/// <param name="sender"></param>
/// <param name="e"></param>
private void toolStripBtnPrintSelected_Click(object sender, EventArgs e)
{
GetDataList();
}
/// <summary>
/// 打印
/// </summary>
/// <param name="sender"></param>
/// <param name="e"></param>
private void toolStripBtnPrint_Click(object sender, EventArgs e)
{
webBrowser1.Print();
}
private void Form1_Load(object sender, EventArgs e)
{
tpl = GetHtmlCode("temp.htm");
}
/// <summary>
/// 刷新模板
/// </summary>
/// <param name="sender"></param>
/// <param name="e"></param>
private void toolStripBtnResetTpl_Click(object sender, EventArgs e)
{
tpl = GetHtmlCode("temp.htm");
}
/// <summary>
/// 打印预览
/// </summary>
/// <param name="sender"></param>
/// <param name="e"></param>
private void toolStripBtnView_Click(object sender, EventArgs e)
{
webBrowser1.ShowPrintPreviewDialog();
}
/// <summary>
/// 打印设置
/// </summary>
/// <param name="sender"></param>
/// <param name="e"></param>
private void toolStripBtnSetUp_Click(object sender, EventArgs e)
{
webBrowser1.ShowPageSetupDialog();
}
/// <summary>
/// 列添加事件(用于添加列头的ToolTipText属性)
/// </summary>
/// <param name="sender"></param>
/// <param name="e"></param>
private void XlsDataGridView_ColumnAdded(object sender, DataGridViewColumnEventArgs e)
{
if (e.Column.Index > 0)
{
e.Column.ToolTipText = "XLSColumn"+e.Column.Index;
}
}
}
public class StringHelper
{
/// <summary>
/// 判断字符串是否包含一个字符串
/// </summary>
/// <param name="oldStr"></param>
/// <param name="obj"></param>
/// <returns></returns>
public bool StringContains(string oldStr, string obj)
{
return oldStr.Contains(obj);
}
}
}
二、Form1设计页面(截了个图)
三、NvelocityHelper.cs类(NVelocity帮助类文件)
using System;
using System.Collections.Generic;
using System.Text;
using System.Web;
using System.IO;
using System.Windows.Forms;
using NVelocity;
using NVelocity.App;
using NVelocity.Context;
using NVelocity.Runtime;
using Commons.Collections;
namespace XlsDataTool
{
public class NvelocityHelper
{
private VelocityEngine velocity = null;
private IContext context = null;
public NvelocityHelper()
{ }
/// <summary>
/// 构造函数
/// </summary>
/// <param name="propsFilename">模板文件夹路径</param>
public NvelocityHelper(string templatDir)
{
Init(templatDir);
}
/// <summary>
/// 初始化NVelocity模块
/// </summary>
/// <param name="templatDir">模板文件夹路径</param>
public void Init(string templatDir)
{
velocity = new VelocityEngine();
使用设置初始化VelocityEngine
ExtendedProperties props = new ExtendedProperties();
props.AddProperty(RuntimeConstants.RESOURCE_LOADER, "file");
props.AddProperty(RuntimeConstants.FILE_RESOURCE_LOADER_PATH, Application.StartupPath + "//" + templatDir);
props.AddProperty(RuntimeConstants.INPUT_ENCODING, "utf-8");
props.AddProperty(RuntimeConstants.OUTPUT_ENCODING, "utf-8");
velocity.Init(props);//初始化;
context = new VelocityContext();//实例化IContext
}
/// <summary>
/// 给模板变量赋值
/// </summary>
/// <param name="key">模板变量</param>
/// <param name="value">要替换的值</param>
public void Assign(string key, object value)
{
if (context == null)
{
context = new VelocityContext();
}
context.Put(key, value);
}
/// <summary>
/// 显示模板
/// </summary>
/// <param name="templatFileName">模板文件名</param>
public string Display(string templatFileName)
{
//从文件中读取模板
Template template = velocity.GetTemplate(templatFileName);
//合并模板
System.IO.StringWriter writer = new System.IO.StringWriter();
template.Merge(context, writer);
return writer.ToString();
输出
//HttpContext.Current.Response.Clear();
//HttpContext.Current.Response.Write(writer.ToString());
//HttpContext.Current.Response.Flush();
//HttpContext.Current.Response.End();
}
}
}