1、DateTime 数字型
System.DateTime currentTime=new System.DateTime();
1.1 取当前年月日时分秒
currentTime=System.DateTime.Now;
1.2 取当前年
int 年=currentTime.Year;
1.3 取当前月
int 月=currentTime.Month;
1.4 取当前日
int 日=currentTime.Day;
1.5 取当前时
int 时=currentTime.Hour;
1.6 取当前分
int 分=currentTime.Minute;
1.7 取当前秒
int 秒=currentTime.Second;
1.8 取当前毫秒
int 毫秒=currentTime.Millisecond; (变量可用中文)
2、Int32.Parse(变量) Int32.Parse("常量")
字符型转换 转为32位数字型
3、 变量.ToString()
字符型转换 转为字符串
12345.ToString("n"); //生成 12,345.00
12345.ToString("C"); //生成 ¥12,345.00
12345.ToString("e"); //生成 1.234500e+004
12345.ToString("f4"); //生成 12345.0000
12345.ToString("x"); //生成 3039 (16进制)
12345.ToString("p"); //生成 1,234,500.00%
4、变量.Length 数字型
取字串长度:
如: string str="中国";
int Len = str.Length ; //Len是自定义变量, str是求测的字串的变量名
5、System.Text.Encoding.Default.GetBytes(变量)
字码转换 转为比特码
如:byte[] bytStr = System.Text.Encoding.Default.GetBytes(str);
然后可得到比特长度:
len = bytStr.Length;
6、System.Text.StringBuilder("")
字符串相加,(+号是不是也一样?)
如:System.Text.StringBuilder sb = new System.Text.StringBuilder("");
sb.Append("中华");
sb.Append("人民");
sb.Append("共和国");
7、变量.Substring(参数1,参数2);
截取字串的一部分,参数1为左起始位数,参数2为截取几位。
如:string s1 = str.Substring(0,2);
8、String user_IP=Request.ServerVariables["REMOTE_ADDR"].ToString();
取远程用户IP地址
9、穿过代理服务器取远程用户真实IP地址:
if(Request.ServerVariables["HTTP_VIA"]!=null){
string user_IP=Request.ServerVariables["HTTP_X_FORWARDED_FOR"].ToString();
}else{
string user_IP=Request.ServerVariables["REMOTE_ADDR"].ToString();
}
10、 Session["变量"];
存取Session值;
如,赋值: Session["username"]="小布什";
取值: Object objName=Session["username"];
String strName=objName.ToString();
清空: Session.RemoveAll();
11、String str=Request.QueryString["变量"];
用超链接传送变量。
如在任一页中建超链接:<a href=Edit.aspx?fbid=23>点击</a>
在Edit.aspx页中取值:String str=Request.QueryString["fdid"];
12、DOC对象.CreateElement("新建节点名");
创建XML文档新节点
13、父节点.AppendChild(子节点);
将新建的子节点加到XML文档父节点下
14、 父节点.RemoveChild(节点);
删除节点
15、Response
Response.Write("字串");
Response.Write(变量);
向页面输出。
Response.Redirect("URL地址");
跳转到URL指定的页面
16、char.IsWhiteSpce(字串变量,位数)——逻辑型
查指定位置是否空字符;
如:
string str="中国 人民";
Response.Write(char.IsWhiteSpace(str,2)); //结果为:True, 第一个字符是0位,2是第三个字符。
17、char.IsPunctuation('字符') --逻辑型
查字符是否是标点符号
如:Response.Write(char.IsPunctuation('A')); //返回:False
18、(int)'字符'
把字符转为数字,查代码点,注意是单引号。
如:
Response.Write((int)'中'); //结果为中字的代码:20013
19、(char)代码
把数字转为字符,查代码代表的字符。
如:
Response.Write((char)22269); //返回“国”字。
20、 Trim()
清除字串前后空格
21 、字串变量.Replace("子字串","替换为")
字串替换
如:
string str="中国";
str=str.Replace("国","央"); //将国字换为央字
Response.Write(str); //输出结果为“中央”
再如:(这个非常实用)
string str="这是<script>脚本";
str=str.Replace("<","<font><</font>"); //将左尖括号替换为<font> 与 < 与 </font> (或换为<,但估计经XML存诸后,再提出仍会还原)
Response.Write(str); //显示为:“这是<script>脚本”
如果不替换,<script>将不显示,如果是一段脚本,将运行;而替换后,脚本将不运行。
这段代码的价值在于:你可以让一个文本中的所有HTML标签失效,全部显示出来,保护你的具有交互性的站点。
具体实现:将你的表单提交按钮脚本加上下面代码:
string strSubmit=label1.Text; //label1是你让用户提交数据的控件ID。
strSubmit=strSubmit.Replace("<","<font><</font>");
然后保存或输出strSubmit。
用此方法还可以简单实现UBB代码。
22、Math.Max(i,j)
取i与j中的最大值
如 int x=Math.Max(5,10); // x将取值 10
23、字串对比一般都用: if(str1==str2){ } , 但还有别的方法:
(1)、
string str1; str2
//语法: str1.EndsWith(str2); __检测字串str1是否以字串str2结尾,返回布尔值.如:
if(str1.EndsWith(str2)){ Response.Write("字串str1是以"+str2+"结束的"); }
(2)、
//语法:str1.Equals(str2); __检测字串str1是否与字串str2相等,返回布尔值,用法同上.
(3)、
//语法 Equals(str1,str2); __检测字串str1是否与字串str2相等,返回布尔值,用法同上.
24、IndexOf() 、LastIndexOf()
查找字串中指定字符或字串首次(最后一次)出现的位置,返回索引值,如:
str1.IndexOf("字"); //查找“字”在str1中的索引值(位置)
str1.IndexOf("字串");//查找“字串”的第一个字符在str1中的索引值(位置)
str1.IndexOf("字串",3,2);//从str1第4个字符起,查找2个字符,查找“字串”的第一个字符在str1中的索引值(位置)
25、Insert()
在字串中指定索引位插入指定字符。如:
str1.Insert(1,"字");在str1的第二个字符处插入“字”,如果str1="中国",插入后为“中字国”;
26、PadLeft()、PadRight()
在字串左(或右)加空格或指定char字符,使字串达到指定长度,如:
<%
string str1="中国人";
str1=str1.PadLeft(10,'1'); //无第二参数为加空格
Response.Write(str1); //结果为“1111111中国人” , 字串长为10
%>
27、Remove()
从指定位置开始删除指定数的字符
字串对比一般都用: if(str1==str2){ } , 但还有别的方法:
1、
string str1; str2
//语法: str1.EndsWith(str2); __检测字串str1是否以字串str2结尾,返回布尔值.如:
if(str1.EndsWith(str2)){ Response.Write("字串str1是以"+str2+"结束的"); }
2、
//语法:str1.Equals(str2); __检测字串str1是否与字串str2相等,返回布尔值,用法同上.
3、
//语法 Equals(str1,str2); __检测字串str1是否与字串str2相等,返回布尔值,用法同上.
IndexOf()
查找字串中指定字符或字串首次出现的位置,返首索引值,如:
str1.IndexOf("字"); //查找“字”在str1中的索引值(位置)
str1.IndexOf("字串");//查找“字串”的第一个字符在str1中的索引值(位置)
str1.IndexOf("字串",3,2);//从str1第4个字符起,查找2个字符,查找“字串”的第一个字符在str1中的索引值(位置)
1.9 取中文日期显示——年月日时分
string strY=currentTime.ToString("f"); //不显示秒
1.10 取中文日期显示_年月
string strYM=currentTime.ToString("y");
1.11 取中文日期显示_月日
string strMD=currentTime.ToString("m");
1.12 取当前年月日,格式为:2003-9-23
string strYMD=currentTime.ToString("d");
1.13 取当前时分,格式为:14:24
string strT=currentTime.ToString("t");
数据导出到Excel的解决方案 [转]
数据导出到Excel的解决方案
//做其它方面的用途,可以对控件部分做适当的修改。
using System;
using System.Data;
using System.Collections;
using System.Collections.Specialized;
using Infragistics.WebUI.UltraWebGrid;
using System.Text.RegularExpressions;
using System.Xml;
using System.Xml.Xsl;
using System.IO;
using System.Xml.XPath;
namespace WEBUI_1
{
/// <summary>
/// GridToExcel 的摘要说明。
/// </summary>
public class GridToExcel
{
/// <summary>
/// 构造函数
/// </summary>
public GridToExcel()
{
//
// TODO: 在此处添加构造函数逻辑
//
}
/// <summary>
/// 根据Grid显示样式,导出数据集数据到指定名称的文件中
/// </summary>
///<param name="strPath">导出路径</param>
///<param name="grid">当前显示Grid</param>
///<param name="ds">当前数据集</param>
public void ExportDataByGridWithXSL(string strPath,UltraWebGrid grid,DataSet ds)
{
DataSet _ds = GetFilterDataSet(grid,ds);
BuildExcel(_ds,strPath);
}
/// <summary>
/// 创建转换格式文件(XSL)
/// </summary>
/// <param name="ds">要导出的数据集</param>
/// <param name="XslPath">xsl文件存放路径</param>
private void GetXSLFile(DataSet ds,string XslPath)
{
string strColumn = "";
string strRow = "";
string dsName=ds.DataSetName;
string tableName=ds.Tables[0].TableName;
string header = dsName + "/" + tableName;
foreach(DataColumn clm in ds.Tables[0].Columns)
{
//特殊字符 <,>,",*,%,(,),& 替换
//*************************************************
//*************************************************
// 符号 xml下的值 excel中的值
// < -------- _x003C_ ------ <
// > -------- _x003E_ ------ >
// " -------- _x0022_ ------ "
// * -------- _x002A_ ------ *
// % -------- _x0025_ ------ %
// & -------- _x0026_ ------ &
// ( -------- _x0028_ ------ (
// ) -------- _x0029_ ------ )
// = -------- _x003D_ ------ =
//*************************************************
//*************************************************
string strClmName = clm.ColumnName;
string strRowName = clm.ColumnName;
if(strClmName.IndexOf("&")!=-1)
strClmName=strClmName.Replace("&","&");
if(strClmName.IndexOf("<")!=-1)
strClmName=strClmName.Replace("<","<");
if(strClmName.IndexOf(">")!=-1)
strClmName=strClmName.Replace(">",">");
if(strClmName.IndexOf(""")!=-1)
strClmName=strClmName.Replace(""",""");
if(strRowName.IndexOf("<")!=-1)
strRowName=strRowName.Replace("<","_x003C_");
if(strRowName.IndexOf(">")!=-1)
strRowName=strRowName.Replace(">","_x003E_");
if(strRowName.IndexOf(""")!=-1)
strRowName=strRowName.Replace(""","_x0022_");
if(strRowName.IndexOf("*")!=-1)
strRowName=strRowName.Replace("*","_x002A_");
if(strRowName.IndexOf("%")!=-1)
strRowName=strRowName.Replace("%","_x0025_");
if(strRowName.IndexOf("&")!=-1)
strRowName=strRowName.Replace("&","_x0026_");
if(strRowName.IndexOf("(")!=-1)
strRowName=strRowName.Replace("(","_x0028_");
if(strRowName.IndexOf(")")!=-1)
strRowName=strRowName.Replace(")","_x0029_");
if(strRowName.IndexOf("=")!=-1)
strRowName=strRowName.Replace("=","_x003D_");
strColumn += "<th>" + strClmName +"</th>" + "rn";
strRow += "<td>" + "<xsl:value-of select=" + """ + strRowName + """ +"/>" + "</td>" + "rn";
}
string str = @"<xsl:stylesheet version=""1.0"" xmlns:xsl=""http://www.w3.org/1999/XSL/Transform"">
<xsl:template match=""/"">
<html xmlns:o=""urn:schemas-microsoft-com:office:office"" xmlns:x=""urn:schemas-microsoft-com:office:excel"" xmlns=""http://www.w3.org/TR/REC-html40"">
<head>
<meta http-equiv=""Content-Type"" content=""text/html;charset=utf-8"" />
<style>
.xl24{mso-style-parent:style0;mso-number-format:""@"";text-align:right;}
</style>
<xml>
<x:ExcelWorkbook>
<x:ExcelWorksheets>
<x:ExcelWorksheet>
<x:Name>Sheet1</x:Name>
<x:WorksheetOptions>
<x:ProtectContents>False</x:ProtectContents>
<x:ProtectObjects>False</x:ProtectObjects>
<x:ProtectScenarios>False</x:ProtectScenarios>
</x:WorksheetOptions>
</x:ExcelWorksheet>
</x:ExcelWorksheets>
</x:ExcelWorkbook>
</xml>
</head>
<body> ";
str += "rn" + @"<table border=""1"" cellpadding=""0"" cellspacing=""0"">
<tr>" + "rn";
str += strColumn;
str += @" </tr>
<xsl:for-each select="""+header+@""">
<tr>";
str += "rn" + strRow;
str += @"</tr>
</xsl:for-each>
</table>
</body>
</html>
</xsl:template>
</xsl:stylesheet> ";
string path = XslPath;
if(File.Exists(path))
{
File.Delete(path);
}
FileStream fs = File.Create(path);
StreamWriter sw=new StreamWriter(fs);
sw.Write(str);
sw.Close();
fs.Close();
}
/// <summary>
/// 根据数据集,生成替换后的xml文件
/// </summary>
/// <param name="ds">数据集合</param>
/// <param name="XmlFilePath">xml文件路径</param>
private void GetXmlFile(DataSet ds,string XmlFilePath)
{
string strXml = ds.GetXml();
if(File.Exists(XmlFilePath))
{
File.Delete(XmlFilePath);
}
FileStream fs1 = File.Create(XmlFilePath);
StreamWriter writer = new StreamWriter(fs1);
writer.Write(strXml);
writer.Close();
fs1.Close();
}
/// <summary>
/// 生成Excel文件
/// </summary>
/// <param name="path">Excel导出全路径</param>
/// <param name="ds">数据集</param>
private void BuildExcel(DataSet ds,string path)
{
if(File.Exists(path))
{
File.Delete(path);
}
string _path = path.Substring(0,path.Length-4);
string _fileXml=_path + ".xml";
string _fileXsl=_path + ".xsl";
string _fileXls=_path+".xls";
try
{
GetXmlFile(ds,_fileXml);
GetXSLFile(ds,_fileXsl);
//Excel转换
XmlDocument doc = new XmlDocument();
doc.Load(_fileXml);
XslTransform xslt = new XslTransform();
xslt.Load(_fileXsl);
XmlElement root = doc.DocumentElement;
XPathNavigator nav = root.CreateNavigator();
XmlTextWriter writer = new XmlTextWriter(_fileXls, null);
xslt.Transform(nav, null, writer, null);
writer.Close();
File.Delete(_fileXml);
File.Delete(_fileXsl);
}
catch
{
throw;
}
}
/// <summary>
/// 更据Grid格式,设置数据集格式
/// </summary>
/// <param name="grid">显示数据的Grid</param>
/// <param name="ds">存储数据的DataSet数据集</param>
/// <returns>设置好的数据集DataSet</returns>
private DataSet GetFilterDataSet(UltraWebGrid grid,DataSet ds)
{
DataColumnCollection col = ds.Tables[0].Columns;
foreach(UltraGridColumn clm in grid.Columns)
{
//如果该列隐藏,那么删除该数据集中的该列数据
if(clm.Hidden)
{
if(col.Contains(clm.Key))
col.Remove(clm.Key);
}
//在显示列的情况下,设置该列的名称为Grid的列标题
else
{
if(col.Contains(clm.Key))
col[clm.Key].ColumnName=clm.HeaderText;
}
}
return ds;
}
}
}
使用链接服务器和T-SQL将查询结果写入Excel
SQL Server有一些工具可用来导出和导入数据。这些简单的工具,例如T-SQL的BULK INSERT语句,或者是BCP工具,都可以将数据以纯文本文件的形式传输。如果需要处理任何一种其他类型的文件的导入导出,则我们必须使用DTS设计器或者DTS向导构建一个DTS包。最终生成的DTS包是一个我们必须测试、维护和操作的独立的对象。而传输数据的工作则变得更加复杂,即使我们只是想要将一个简单的Excel文件传输到文件系统中。
这里,我建议使用一个简单,但是很有用的T-SQL 存储程序,它可以通过使用链接服务器(linked server)技术将数据导出到Excel 中。
为了实现导出,你必须首先创建一个空的有固定名字的Excel文件,并将其放置在服务器上。我把它命名为Empty.xls,并放置在c:temp的目录下。这个文件不会被删除,并且在装入数据之前,作为目标Excel文件的模板使用。
Empty.xls文件被构建的时候,只含有一个工作页,名为ExcelTable,其中的第一行(仅有的一行)包含如下字母: A,B,C,...Z。这些字母可作为Excel表的列名称。这意味着在一个查询中,我们可以导出26个列。(给定的存储程序代码可被修改,以支持结果集中含有更多的列的情况。只需要在Excel模板中简单地书写F1, F2 ,F3...,然后更改程序中相应列的列表即可反映出变化了。)
sp_write2Excel是一个T-SQL存储过程,它获取目标Excel文件的名字和路径,结果集中列的数量,以及T-SQL查询。在查询中应该使用转换函数将所有的非字符串数据导入列中,因为最终的Excel单元中数据实际上都是字符串格式的。
这个过程将empty.xls模板文件拷贝到新的目标Excel文件中。然后它再构建一个链接服务器到刚才的文件中,并使用动态的T-SQL来构建这个Excel文件,并且使用插入/选择语句来将数据写入其中。
以下是程序代码:
Create proc sp_write2Excel (@fileName varchar(100),
@NumOfColumns tinyint,
@query varchar(200))
as
begin
declare @dosStmt varchar(200)
declare @tsqlStmt varchar(500)
declare @colList varchar(200)
declare @charInd tinyint
set nocount on
-- 构建列的列表 A,B,C ...
-- 直到达到列的数量.
set @charInd=0
set @colList = 'A'
while @charInd < @NumOfColumns - 1
begin
set @charInd = @charInd + 1
set @colList = @colList + ',' + char(65 + @charInd)
end
-- 创建一个空的Excel 文件作为目标文件,通过拷贝模板Excel 文件来命名
set @dosStmt = ' copy c:tempempty.xls ' + @fileName
exec master..xp_cmdshell @dosStmt
-- 创建一个“临时”的链接服务器到刚才的文件中,以用于“导出”数据
EXEC sp_addlinkedserver 'ExcelSource',
'Jet 4.0',
'Microsoft.Jet.OLEDB.4.0',
@fileName,
NULL,
'Excel 5.0'
-- 构建一个T-SQL 语句,用于实际导出查询结果
-- 到目标链接服务器上的表中
set @tsqlStmt = 'Insert ExcelSource...[ExcelTable$] ' + ' ( ' + @colList + ' ) '+ @query
print @tsqlStmt
-- 执行动态的 TSQL语句
exec (@tsqlStmt)
-- 删除链接服务器
EXEC sp_dropserver 'ExcelSource'
set nocount off
end
GO
程序使用实例:
Use master
go
exec sp_write2Excel
--目标excel文件
'c:tempNorthProducts.xls' ,
-- 结果中列的数量
3,
-- 将要导出结果的查询
'select convert(varchar(10),ProductId),
ProductName,
Convert (varchar(20),UnitPrice) from Northwind..Products'
结论,这个程序可作为一个通用的工具将数据导出到Excel工作页中,而BCP工具则只能将数据导出到文本文件中。
我们可以使用这个程序来代替DTS包设计器,以及DTS向导,每当需要调用这样的动作的时候,都可以用它将数据导出到excel 文件中。
c#实现的获取并打印DataGrid中的数据[原创]
今年毕业了,好不容易在上海一家软件公司找到工作
最近才实习一个月多一点,在一个项目组里写写代码什么的,也算是我的毕业设计.
有个报表打印的程序要我来写,是从DataGrid中打印出来的^
说真的,c#本来就不熟悉,何况还是做这么麻烦的事……于是,我先在网上找了一下,也发现不少相关的代码
但是,不是写的太空洞,就是用别的语言,如vb写的,虽然还能看得懂,但却用不起来
几乎没有能够找到可以用的代码,只有一点借鉴的意义吧
于是,我自己花了一天的时间,完完整整地写了下来,贴在这里供网友参考,希望高手们给点意见。
说明:我是在vs2003.net里做的,所以有些控件布置什么的就不做说明,和一般的打印程序一样,都只有那么几个
具体的名字什么的,可以根据我的定义名称来判断,比如,dlgPrint就是一个打印控件等。
using System;
using System.IO;
using System.Drawing;
using System.Drawing.Printing;
using System.Data;
using System.Windows.Forms;
//这里隐去公司内部的项目类空间
namespace *.*.Manage//这里隐去公司内部的项目类空间
{
/// <summary>
///
/// </summary>
public class frmCourseTable : System.Windows.Forms.Form
{
private System.Windows.Forms.ToolBar toolBar1;
private System.Windows.Forms.ImageList imageList1;
private System.Windows.Forms.ToolBarButton btnPreView;
private System.Windows.Forms.ToolBarButton btnPrint;
private System.Windows.Forms.ToolBarButton btnSave;
private System.Windows.Forms.ToolBarButton btnClose;
private System.Windows.Forms.ToolBarButton btnSeparator2;
private System.Windows.Forms.ToolBarButton btnSeparator1;
private System.Windows.Forms.DataGrid dgClasses;
private System.Windows.Forms.DataGridTableStyle dataGridTableStyle1;
private System.Windows.Forms.DataGridTextBoxColumn dataGridTextBoxColumn1;
private System.Windows.Forms.DataGridTextBoxColumn dataGridTextBoxColumn2;
private System.Windows.Forms.DataGridTextBoxColumn dataGridTextBoxColumn3;
private System.Windows.Forms.DataGridTextBoxColumn dataGridTextBoxColumn4;
private System.Windows.Forms.DataGridTextBoxColumn dataGridTextBoxColumn5;
private System.Windows.Forms.DataGridTextBoxColumn dataGridTextBoxColumn6;
private System.Windows.Forms.DataGridTextBoxColumn dataGridTextBoxColumn7;
private System.Windows.Forms.DataGridTextBoxColumn dataGridTextBoxColumn8;
private System.Windows.Forms.DataGridTextBoxColumn dataGridTextBoxColumn9;
private System.ComponentModel.IContainer components = null;
private System.Windows.Forms.PrintPreviewDialog dlgPreview;
private System.Drawing.Printing.PrintDocument printCourseDoc;
private System.Windows.Forms.ToolBarButton btnPrintSetup;
private System.Windows.Forms.PageSetupDialog dlgPrintSetup;
private System.Windows.Forms.PrintDialog dlgPrint;
private System.Windows.Forms.PrintPreviewDialog printPreviewDialog1;
private string fileName = "未命名";
private DataTable dgTable;
private int ColsCount;//列数
private int PrintRecordComplete = 0;//已经打印完的记录行数
private int PrintingPageNumber = 0;//正要打印的页,初始为0
private int printLines;//当前页共要分成多少行,其值由“纵向打印”还是“横向打印”来决定
//是针对整个页面来说的,不管是否有内容。该常量只用于划分单元格,不做打印之用
private int PrintRecordNumber = 45;//每页要打印的记录的行数,初始设定
//针对每页要打印的记录的行数来说的,注意与pringLines的区别,一般来说该常量数值应小于printLines
private int PageRecordNumber = 0;//当前要打印的行数,由计算得到
private int PrintingLine = 0;//当前正在打印的行数
private PointF DrawPoint;//(标题的)位置在顶部的正中央
private Brush DrawBrush = Brushes.Black;//画笔颜色
int x;
int y;
int X_unit;
int Y_unit;
public frmCourseTable()
{
InitializeComponent();
}
/// <summary>
/// 清理所有正在使用的资源。
/// </summary>
protected override void Dispose( bool disposing )
{
if( disposing )
{
if(components != null)
{
components.Dispose();
}
}
base.Dispose( disposing );
}
private void frmCourseTable_Load(object sender, System.EventArgs e)
{
try
{
Class cla = new Class();//这里是公司内部的项目类
dgTable = cla.ListAllClasses();
dgTable.TableName = "Result";
dgClasses.DataSource = dgTable;
dgClasses.CaptionText = "课程列表";
}
catch(Exception ex)
{
Common.ShowErrorDetail(ex.Message);
}
}
#region Windows 窗体设计器生成的代码
/// <summary>
/// 设计器支持所需的方法 - 不要使用代码编辑器修改
/// 此方法的内容。
/// </summary>
private void InitializeComponent()
{
this.components = new System.ComponentModel.Container();
System.Resources.ResourceManager resources = new System.Resources.ResourceManager(typeof(frmCourseTable));
this.toolBar1 = new System.Windows.Forms.ToolBar();
this.btnPreView = new System.Windows.Forms.ToolBarButton();
this.btnPrintSetup = new System.Windows.Forms.ToolBarButton();
this.btnPrint = new System.Windows.Forms.ToolBarButton();
this.btnSeparator1 = new System.Windows.Forms.ToolBarButton();
this.btnSave = new System.Windows.Forms.ToolBarButton();
this.btnSeparator2 = new System.Windows.Forms.ToolBarButton();
this.btnClose = new System.Windows.Forms.ToolBarButton();
this.imageList1 = new System.Windows.Forms.ImageList(this.components);
this.dgClasses = new System.Windows.Forms.DataGrid();
this.dataGridTableStyle1 = new System.Windows.Forms.DataGridTableStyle();
this.dataGridTextBoxColumn1 = new System.Windows.Forms.DataGridTextBoxColumn();
this.dataGridTextBoxColumn2 = new System.Windows.Forms.DataGridTextBoxColumn();
this.dataGridTextBoxColumn3 = new System.Windows.Forms.DataGridTextBoxColumn();
this.dataGridTextBoxColumn4 = new System.Windows.Forms.DataGridTextBoxColumn();
this.dataGridTextBoxColumn5 = new System.Windows.Forms.DataGridTextBoxColumn();
this.dataGridTextBoxColumn6 = new System.Windows.Forms.DataGridTextBoxColumn();
this.dataGridTextBoxColumn7 = new System.Windows.Forms.DataGridTextBoxColumn();
this.dataGridTextBoxColumn8 = new System.Windows.Forms.DataGridTextBoxColumn();
this.dataGridTextBoxColumn9 = new System.Windows.Forms.DataGridTextBoxColumn();
this.dlgPreview = new System.Windows.Forms.PrintPreviewDialog();
this.printCourseDoc = new System.Drawing.Printing.PrintDocument();
this.dlgPrintSetup = new System.Windows.Forms.PageSetupDialog();
this.dlgPrint = new System.Windows.Forms.PrintDialog();
this.printPreviewDialog1 = new System.Windows.Forms.PrintPreviewDialog();
((System.ComponentModel.ISupportInitialize)(this.dgClasses)).BeginInit();
this.SuspendLayout();
//
// toolBar1
//
this.toolBar1.AutoSize = false;
this.toolBar1.Buttons.AddRange(new System.Windows.Forms.ToolBarButton[] {
this.btnPreView,
this.btnPrintSetup,
this.btnPrint,
this.btnSeparator1,
this.btnSave,
this.btnSeparator2,
this.btnClose});
this.toolBar1.DropDownArrows = true;
this.toolBar1.Font = new System.Drawing.Font("宋体", 9F, System.Drawing.FontStyle.Regular, System.Drawing.GraphicsUnit.Point, ((System.Byte)(134)));
this.toolBar1.ImageList = this.imageList1;
this.toolBar1.Location = new System.Drawing.Point(0, 0);
this.toolBar1.Name = "toolBar1";
this.toolBar1.ShowToolTips = true;
this.toolBar1.Size = new System.Drawing.Size(416, 32);
this.toolBar1.TabIndex = 0;
this.toolBar1.TextAlign = System.Windows.Forms.ToolBarTextAlign.Right;
this.toolBar1.ButtonClick += new System.Windows.Forms.ToolBarButtonClickEventHandler(this.toolBar1_ButtonClick);
//
// btnPreView
//
this.btnPreView.ImageIndex = 0;
this.btnPreView.ToolTipText = "打印预览";
//
// btnPrintSetup
//
this.btnPrintSetup.ImageIndex = 3;
this.btnPrintSetup.ToolTipText = "打印设置";
//
// btnPrint
//
this.btnPrint.ImageIndex = 1;
this.btnPrint.ToolTipText = "打印";
//
// btnSeparator1
//
this.btnSeparator1.Style = System.Windows.Forms.ToolBarButtonStyle.Separator;
//
// btnSave
//
this.btnSave.ImageIndex = 2;
this.btnSave.ToolTipText = "保存";
//
// btnSeparator2
//
this.btnSeparator2.Style = System.Windows.Forms.ToolBarButtonStyle.Separator;
//
// btnClose
//
this.btnClose.Text = "关闭";
this.btnClose.ToolTipText = "关闭";
//
// imageList1
//
this.imageList1.ImageSize = new System.Drawing.Size(16, 16);
this.imageList1.ImageStream = ((System.Windows.Forms.ImageListStreamer)(resources.GetObject("imageList1.ImageStream")));
this.imageList1.TransparentColor = System.Drawing.Color.Transparent;
//
// dgClasses
//
this.dgClasses.CaptionVisible = false;
this.dgClasses.DataMember = "";
this.dgClasses.Dock = System.Windows.Forms.DockStyle.Fill;
this.dgClasses.HeaderForeColor = System.Drawing.SystemColors.ControlText;
this.dgClasses.Location = new System.Drawing.Point(0, 32);
this.dgClasses.Name = "dgClasses";
this.dgClasses.ReadOnly = true;
this.dgClasses.Size = new System.Drawing.Size(416, 261);
this.dgClasses.TabIndex = 1;
this.dgClasses.TableStyles.AddRange(new System.Windows.Forms.DataGridTableStyle[] {
this.dataGridTableStyle1});
//
// dataGridTableStyle1
//
this.dataGridTableStyle1.DataGrid = this.dgClasses;
this.dataGridTableStyle1.GridColumnStyles.AddRange(new System.Windows.Forms.DataGridColumnStyle[] {
this.dataGridTextBoxColumn1,
this.dataGridTextBoxColumn2,
this.dataGridTextBoxColumn3,
this.dataGridTextBoxColumn4,
this.dataGridTextBoxColumn5,
this.dataGridTextBoxColumn6,
this.dataGridTextBoxColumn7,
this.dataGridTextBoxColumn8,
this.dataGridTextBoxColumn9});
this.dataGridTableStyle1.HeaderForeColor = System.Drawing.SystemColors.ControlText;
this.dataGridTableStyle1.MappingName = "Result";
this.dataGridTableStyle1.ReadOnly = true;
//
// dataGridTextBoxColumn1
//
this.dataGridTextBoxColumn1.Format = "";
this.dataGridTextBoxColumn1.FormatInfo = null;
this.dataGridTextBoxColumn1.HeaderText = "课程号";
this.dataGridTextBoxColumn1.MappingName = "ID";
this.dataGridTextBoxColumn1.Width = 55;
//
// dataGridTextBoxColumn2
//
this.dataGridTextBoxColumn2.Format = "";
this.dataGridTextBoxColumn2.FormatInfo = null;
this.dataGridTextBoxColumn2.HeaderText = "教师号";
this.dataGridTextBoxColumn2.MappingName = "TeachNo";
this.dataGridTextBoxColumn2.Width = 40;
//
// dataGridTextBoxColumn3
//
this.dataGridTextBoxColumn3.Format = "";
this.dataGridTextBoxColumn3.FormatInfo = null;
this.dataGridTextBoxColumn3.HeaderText = "课程名称";
this.dataGridTextBoxColumn3.MappingName = "Name";
this.dataGridTextBoxColumn3.Width = 150;
//
// dataGridTextBoxColumn4
//
this.dataGridTextBoxColumn4.Format = "";
this.dataGridTextBoxColumn4.FormatInfo = null;
this.dataGridTextBoxColumn4.HeaderText = "教师名称";
this.dataGridTextBoxColumn4.MappingName = "TeachName";
this.dataGridTextBoxColumn4.Width = 90;
//
// dataGridTextBoxColumn5
//
this.dataGridTextBoxColumn5.Format = "";
this.dataGridTextBoxColumn5.FormatInfo = null;
this.dataGridTextBoxColumn5.HeaderText = "学分";
this.dataGridTextBoxColumn5.MappingName = "Credit";
this.dataGridTextBoxColumn5.Width = 10;
//
// dataGridTextBoxColumn6
//
this.dataGridTextBoxColumn6.Format = "";
this.dataGridTextBoxColumn6.FormatInfo = null;
this.dataGridTextBoxColumn6.HeaderText = "实际人数";
this.dataGridTextBoxColumn6.MappingName = "RealNum";
this.dataGridTextBoxColumn6.Width = 10;
//
// dataGridTextBoxColumn7
//
this.dataGridTextBoxColumn7.Format = "";
this.dataGridTextBoxColumn7.FormatInfo = null;
this.dataGridTextBoxColumn7.HeaderText = "额定人数";
this.dataGridTextBoxColumn7.MappingName = "TOTALNUM";
this.dataGridTextBoxColumn7.Width = 10;
//
// dataGridTextBoxColumn8
//
this.dataGridTextBoxColumn8.Format = "";
this.dataGridTextBoxColumn8.FormatInfo = null;
this.dataGridTextBoxColumn8.HeaderText = "上课时间";
this.dataGridTextBoxColumn8.MappingName = "TimeText";
this.dataGridTextBoxColumn8.Width = 120;
//
// dataGridTextBoxColumn9
//
this.dataGridTextBoxColumn9.Format = "";
this.dataGridTextBoxColumn9.FormatInfo = null;
this.dataGridTextBoxColumn9.HeaderText = "上课地点";
this.dataGridTextBoxColumn9.MappingName = "Room";
this.dataGridTextBoxColumn9.Width = 120;
//
// dlgPreview
//
this.dlgPreview.AutoScrollMargin = new System.Drawing.Size(0, 0);
this.dlgPreview.AutoScrollMinSize = new System.Drawing.Size(0, 0);
this.dlgPreview.ClientSize = new System.Drawing.Size(400, 300);
this.dlgPreview.Document = this.printCourseDoc;
this.dlgPreview.Enabled = true;
this.dlgPreview.Icon = ((System.Drawing.Icon)(resources.GetObject("dlgPreview.Icon")));
this.dlgPreview.Location = new System.Drawing.Point(230, 20);
this.dlgPreview.MinimumSize = new System.Drawing.Size(375, 250);
this.dlgPreview.Name = "dlgPreview";
this.dlgPreview.TransparencyKey = System.Drawing.Color.Empty;
this.dlgPreview.Visible = false;
//
// printCourseDoc
//
this.printCourseDoc.BeginPrint += new System.Drawing.Printing.PrintEventHandler(this.printCourseDoc_BeginPrint);
this.printCourseDoc.PrintPage += new System.Drawing.Printing.PrintPageEventHandler(this.printCourseDoc_PrintPage);
//
// dlgPrintSetup
//
this.dlgPrintSetup.Document = this.printCourseDoc;
//
// dlgPrint
//
this.dlgPrint.Document = this.printCourseDoc;
//
// printPreviewDialog1
//
this.printPreviewDialog1.AutoScrollMargin = new System.Drawing.Size(0, 0);
this.printPreviewDialog1.AutoScrollMinSize = new System.Drawing.Size(0, 0);
this.printPreviewDialog1.ClientSize = new System.Drawing.Size(400, 300);
this.printPreviewDialog1.Enabled = true;
this.printPreviewDialog1.Icon = ((System.Drawing.Icon)(resources.GetObject("printPreviewDialog1.Icon")));
this.printPreviewDialog1.Location = new System.Drawing.Point(176, 176);
this.printPreviewDialog1.MinimumSize = new System.Drawing.Size(375, 250);
this.printPreviewDialog1.Name = "printPreviewDialog1";
this.printPreviewDialog1.TransparencyKey = System.Drawing.Color.Empty;
this.printPreviewDialog1.Visible = false;
//
// frmCourseTable
//
this.AutoScaleBaseSize = new System.Drawing.Size(6, 14);
this.ClientSize = new System.Drawing.Size(416, 293);
this.Controls.Add(this.dgClasses);
this.Controls.Add(this.toolBar1);
this.Name = "frmCourseTable";
this.StartPosition = System.Windows.Forms.FormStartPosition.CenterParent;
this.Text = "课程列表";
this.Load += new System.EventHandler(this.frmCourseTable_Load);
((System.ComponentModel.ISupportInitialize)(this.dgClasses)).EndInit();
this.ResumeLayout(false);
}
#endregion
private void toolBar1_ButtonClick(object sender, System.Windows.Forms.ToolBarButtonClickEventArgs e)
{
try
{
if(e.Button == btnPreView)
{
dlgPreview.ShowDialog();//打印预览
}
if(e.Button == btnPrintSetup)
{
dlgPrintSetup.ShowDialog();//打印设置
}
if(e.Button == btnPrint)
{
if(dlgPrint.ShowDialog() == DialogResult.OK)
{
printCourseDoc.Print();//打印
}
}
if(e.Button == btnSave)
{
SaveFileDlg();//保存
}
if(e.Button == btnClose)
{
this.Close();//关闭
}
}
catch(Exception ex)
{
MessageBox.Show(ex.Message, "打印出现错误",
MessageBoxButtons.OK, MessageBoxIcon.Exclamation);
}
}
protected void SaveFileDlg()
{//这里保存文件的代码未完成
}
protected void SaveFile()
{//这里保存文件的代码未完成
}
//从“打印设置PrintSetup”中获取相关参数,进行打印
//这里有个问题:如果选择纸张大小为“自定义大小”,那么在PrintPreview的时候就会出错,为什么呢?
private void printCourseDoc_PrintPage(object sender, System.Drawing.Printing.PrintPageEventArgs e)
{
int Cols = 0;
x = e.MarginBounds.Left;//纸张可写处的最左边
y = e.MarginBounds.Top;//纸张可写处的最上端
IsFullPage(dgTable, PrintingPageNumber, PrintRecordNumber);
int columnCounts = 0;//定义DataGrid中的列数
string[] colText = new string[columnCounts];//定义一个与DataGrid中的列数相同大小的数组,存放其中的字段名称
string[] colID = new string[columnCounts];//定义一个存放字段属性值(如ID,TeacherName)等的数组,打印DataGrid中的数据时要用到
int[] colSize = new int[columnCounts];//定义一个存放各个字段大小的数组
//取得DataGrid中的列数,以及各个列的名称,并赋给ColText数组
foreach(DataGridTableStyle myGridStyle in dgClasses.TableStyles)
{
string[] headerText = new string[myGridStyle.GridColumnStyles.Count];
string[] headerID = new string[myGridStyle.GridColumnStyles.Count];
int[] columnSize = new int[myGridStyle.GridColumnStyles.Count];
//遍历dgClasses中的每个表所有的字段
foreach(DataGridColumnStyle myColumnStyle in myGridStyle.GridColumnStyles)
{
headerText[columnCounts++] = myColumnStyle.HeaderText;//获得字段名称,如“学号”等
headerID[columnCounts-1] = myColumnStyle.MappingName;//获取字段属性值,如“ID”等
columnSize[columnCounts-1] = myColumnStyle.Width;
}
colText = headerText;//赋给前者
colID = headerID;//赋给前者
colSize = columnSize;//赋给前者
}
try
{
//将当前页分成基本的单元
if(printCourseDoc.DefaultPageSettings.Landscape == true)
{
X_unit = e.MarginBounds.Height / (columnCounts + 5);//[横向打印时]除以“要打印的字段总数+5”,得到纵向间隔大小
Y_unit = e.MarginBounds.Width / printLines;
}
else
{
X_unit = e.MarginBounds.Width / (columnCounts + 5);//[纵向打印]除以“要打印的字段总数+5”,得到横向间隔大小
Y_unit = e.MarginBounds.Height / printLines;
}
}
catch(Exception ex)
{
Common.ShowErrorDetail(ex.Message);
}
//打印文档标题,自定义
string strPrintTitle = dgClasses.CaptionText;//文档标题,这里为“课程列表”
DrawPoint = new PointF(x + e.MarginBounds.Width/2 - 50, y );//设定标题的打印位置坐标(x,y)=(矩形最左边坐标+矩形的宽度的一半,矩形最上边的坐标)
e.Graphics.DrawString(strPrintTitle, PrintFont("宋体", 20), DrawBrush, DrawPoint);//打印文档标题
y += Y_unit * 2;//打印完标题,往下移动两个“Y_unit”单位
//打印列名
for(Cols=0;Cols<columnCounts;Cols++)
{
if(Cols == 0)
{
DrawPoint.X = X_unit;//如果是第一列,则从X_unit开始
}
else
{
DrawPoint.X += colSize[Cols-1] + X_unit;//如果是第二个以后,则从每次往前移动一个单元格和前一个的字段大小
}
DrawPoint.Y = y;//设定当前列名的打印位置
e.Graphics.DrawString(colText[Cols], PrintFont("宋体", 10), DrawBrush, DrawPoint);//打印所有列名
}
DrawPoint = new PointF(X_unit, y);
DrawLine(DrawPoint, e);//在列名下面打印一条黑色直线
y += Y_unit;//打印完全部列名,往下移动“Y_unit”个单位
//打印DataGrid中的数据
while(PrintingLine<PageRecordNumber)
{
DataRow dgRow = dgTable.Rows[PrintRecordComplete];
IsFullPage(dgTable, PrintingPageNumber, PrintRecordNumber);//判断最后一页的记录数是否可以打满一页,否则出错。
for(Cols=0;Cols<columnCounts;Cols++)
{
if(Cols == 0)
{
DrawPoint.X = X_unit;
}
else
{
DrawPoint.X += colSize[Cols-1] + X_unit;
}
DrawPoint.Y = y;
e.Graphics.DrawString(dgRow[colID[Cols]].ToString(), PrintFont("宋体", 10), DrawBrush, DrawPoint);
}
y += Y_unit;//打印完一行,就往下移动“Y_unit”个单位
PrintingLine += 1;//正在打印的行数+1
PrintRecordComplete += 1;//已经打印的记录数+1
if(y > e.MarginBounds.Bottom)
{
DrawPoint.X = X_unit * 1;
DrawPoint.Y = y;
DrawLine(DrawPoint, e);//在每个页面的底尾打印一条黑色直线
e.HasMorePages = true;//如果已经到达纸张底部,则开始新页
PrintingPageNumber += 1;//正要打印的页数+1
PageRecordNumber = 0;//将当前要打印的行数置0
PrintingLine = 0;//将正在打印的行数置0
return;
}
}
e.HasMorePages = false;
}
//只调用一次,用于初始化
private void printCourseDoc_BeginPrint(object sender, System.Drawing.Printing.PrintEventArgs e)
{
dgTable = (DataTable)dgClasses.DataSource;
ColsCount = dgTable.Columns.Count;
//当前页是横向还是纵向打印,并计算当前页总共可以打印的行数
if(printCourseDoc.DefaultPageSettings.Landscape == false)
{
printLines = printCourseDoc.DefaultPageSettings.PaperSize.Height / (PrintFont("宋体", 10).Height + 10);//纵向打印的情况
}
else
{
printLines = printCourseDoc.DefaultPageSettings.PaperSize.Width / (PrintFont("宋体", 10).Height + 10);//横向打印的情况
}
}
//计算,余下的记录条数是否还可以在一页打印,不满一页时为假
protected void IsFullPage(DataTable dgTable, int PrintingPageNumber, int PrintRecordNumber)
{
//计算,余下的记录条数是否还可以在一页打印,不满一页时为假
if(dgTable.Rows.Count - PrintingPageNumber * PrintRecordNumber >= PrintRecordNumber)
{
PageRecordNumber = PrintRecordNumber;//余下的条数还可以打满一页,将“每页可打印条数”赋给“当前要打印的行数”
}
else
{
PageRecordNumber = (dgTable.Rows.Count - PrintingPageNumber * PrintRecordNumber) % PrintRecordNumber;
}
}
//Draw a line with a black pen.
protected void DrawLine(PointF point, System.Drawing.Printing.PrintPageEventArgs e)
{
Pen blackPen = new Pen(System.Drawing.Color.Black, 1);
e.Graphics.DrawLine(blackPen, point.X, point.Y + PrintFont("宋体", 10).Height, point.X * ColsCount, point.Y + PrintFont("宋体", 10).Height);
}
//返回字体设置
protected Font PrintFont(string font, int size)
{
return new Font(font,size);
}
}
}