ExcelObject.cs:用于表示Excel 中单元格数据,样式等信息关信息的对象
代码如下:
/// <summary>
///单元格对齐方式
/// None:默认对齐方式(水平默认为左对齐,垂直默认为居中对齐)
/// Left:水平为左对齐,垂直为上对齐
/// Center:均为居中对齐
/// Right:水平为右对齐、垂直为下对齐
/// </summary>
public enum Alignment { None = -1, Left = 0, Center = 1, Right = 2 }
/// <summary>
/// 要显示的格式
/// 0:文本类型
/// 1:数字
/// 2:货币类型
/// 3:比分比
/// </summary>
public enum CellDisplayType { STRING = 0, NUMBER = 1, CURRENCURY = 2, PERCENT = 3 }
/// <summary>
/// 用于表示当前单元格的样式信息
/// </summary>
[Serializable]
public class CellStyle
{
private string m_StyleName = "Default"; //样式名称
private GDIBorderWidth m_BorderWidth = new GDIBorderWidth();//边框宽度
private Alignment m_HorAlignment = Alignment.None; //水平对齐方式
private Alignment m_VerAlignment = Alignment.None; //垂直对齐方式
private string m_FontName = "宋体"; //宋体名称
private string m_FontSize = "10"; //字体大小
private Color m_FontColor = Color.Black; //字体颜色
private bool m_Bold = false; //是否粗体
private bool m_Italic = false; //是否倾斜
private bool m_Underline = false; //是否下划线
private CellDisplayType m_Format = CellDisplayType.STRING; //显示格式
private byte m_Number = 2; //小数位数
[DefaultValue("Default")]
public string StyleName
{
get { return m_StyleName; }
set { m_StyleName = value; }
}
[DefaultValue(0)]
public GDIBorderWidth BorderWidth
{
get { return m_BorderWidth; }
set { m_BorderWidth = value; }
}
[DefaultValue(0)]
public Alignment HorAlignment
{
get { return m_HorAlignment; }
set { m_HorAlignment = value; }
}
public Alignment VerAligment
{
get { return m_VerAlignment; }
set { m_VerAlignment = value; }
}
[DefaultValue("宋体")]
public string FontName
{
get { return m_FontName; }
set { m_FontName = value; }
}
[DefaultValue("12")]
public string FontSize
{
get { return m_FontSize; }
set { m_FontSize = value; }
}
[DefaultValue(typeof(Color), "#000000")]
public Color FontColor
{
get { return m_FontColor; }
set { m_FontColor = value; }
}
[DefaultValue(false)]
public bool Bold
{
get { return m_Bold; }
set { m_Bold = value; }
}
[DefaultValue(false)]
public bool Italic
{
get { return m_Italic; }
set { m_Italic = value; }
}
[DefaultValue(false)]
public bool Underline
{
get { return m_Underline; }
set { m_Underline = value; }
}
[DefaultValue(0)]
public CellDisplayType Format
{
get { return m_Format; }
set { m_Format = value; }
}
[DefaultValue(2)]
public byte Number
{
get { return m_Number; }
set { m_Number = value; }
}
}
/// <summary>
/// 用于表示当前单元格的结构信息
/// </summary>
[Serializable]
public class CellStruct
{
private int m_RowIndex = 0; //当前单元格行索引
private int m_ColumnIndex = 0; //当前单元格列索引
private int m_ColumnSpan = 1; //当前单元格包含列数
private int m_RowSpan = 1; //当前单元格包含行数
private int m_Width; //当前单元格宽度
private int m_Height; //当前单元格高度
private CellStyle m_Style; //当前单元格样式
private string m_Value; //当前单元格值
[DefaultValue(0)]
public int RowIndex
{
get { return m_RowIndex; }
set { m_RowIndex = value; }
}
[DefaultValue(0)]
public int ColumnIndex
{
get { return m_ColumnIndex; }
set { m_ColumnIndex = value; }
}
[DefaultValue(1)]
public int ColumnSpan
{
get { return m_ColumnSpan; }
set { m_ColumnSpan = value; }
}
[DefaultValue(1)]
public int RowSpan
{
get { return m_RowSpan; }
set { m_RowSpan = value; }
}
[DefaultValue(1)]
public int Width
{
get { return m_Width; }
set { m_Width = value; }
}
[DefaultValue(1)]
public int Height
{
get { return m_Height; }
set { m_Height = value; }
}
public CellStyle Style
{
get { return m_Style; }
set { m_Style = value; }
}
public string Value
{
get { return m_Value; }
set { m_Value = value; }
}
}
/// <summary>
/// 用于表示表格边框宽度
/// </summary>
[Serializable]
public class GDIBorderWidth
{
private byte m_TopWidth = 0; //上边框
private byte m_LeftWdith = 0; //左边框
private byte m_RigthWidth = 0; //右边框
private byte m_BottomWidth = 0; //下边框
[DefaultValue(0)]
public byte LeftWdith
{
get { return m_LeftWdith; }
set { m_LeftWdith = value; }
}
[DefaultValue(0)]
public byte TopWidth
{
get { return m_TopWidth; }
set { m_TopWidth = value; }
}
[DefaultValue(0)]
public byte RigthWidth
{
get { return m_RigthWidth; }
set { m_RigthWidth = value; }
}
[DefaultValue(0)]
public byte BottomWidth
{
get { return m_BottomWidth; }
set { m_BottomWidth = value; }
}
}
/// <summary>
/// 颜色处理类
/// </summary>
public class ExcelConvert
{
/// <summary>
///
/// </summary>
/// <param name="value"></param>
/// <returns></returns>
public static Color StringToColor(string value)
{
return System.Drawing.ColorTranslator.FromHtml(value);
}
/// <summary>
/// 将指定的点单位转换为对应的像素单位值
/// </summary>
/// <param name="value">要转换的数据</param>
/// <returns></returns>
public static double PointToPixels(double value)
{
return Math.Round(value * 99.3 / 72);
}
}
ExcelXmlAnalysis.cs 用于实现对Execl格式的xml进行解析
代码如下:
/// <summary>
/// 用于实现对Execl的解析
/// </summary>
[Serializable]
public class ExcelXmlAnalysis
{
//单元格集合信息
private CellStruct[,] Excel_Cells;
//行高集合信息
private Hashtable m_RowsHeight = new Hashtable();
//列宽信息信息
private Hashtable m_ColumnsWidth = new Hashtable();
//默认列宽
private double m_DefaultWidth = 0;
//默认行高
private double m_DefaultHeight = 0;
//数据行数
private int m_RowsCount=0;
//表示数据列数
private int m_ColumnsCount = 0;
//页面大小设置索引
private int m_PaperSizeIndex = 0;
//页边距
private Margins m_PageMargins = new Margins();
#region 属性
public CellStruct[,] Cells
{
get { return Excel_Cells; }
set { Excel_Cells = value; }
}
public Hashtable RowsHeight
{
get { return m_RowsHeight; }
set { m_RowsHeight = value; }
}
public Hashtable ColumnsWidth
{
get { return m_ColumnsWidth; }
set { m_ColumnsWidth = value; }
}
public double DefaultWidth
{
get { return m_DefaultWidth; }
set { m_DefaultWidth = value; }
}
public double DefaultHeight
{
get { return m_DefaultHeight; }
set { m_DefaultHeight = value; }
}
public int RowsCount
{
get { return m_RowsCount; }
set { m_RowsCount = value; }
}
public int ColumnsCount
{
get { return m_ColumnsCount; }
set { m_ColumnsCount = value; }
}
public int PaperSizeIndex
{
get { return m_PaperSizeIndex; }
set { m_PaperSizeIndex = value; }
}
public Margins PageMargins
{
get { return m_PageMargins; }
set { m_PageMargins = value; }
}
#endregion
/// <summary>
/// 创建当前对象的附本
/// </summary>
/// <returns></returns>
public ExcelXmlAnalysis Copy()
{
ExcelXmlAnalysis xml = new ExcelXmlAnalysis();
xml.Cells = new CellStruct[this.Cells.GetLength(0), this.Cells.GetLength(1)];
for (int i = 0; i < xml.Cells.GetLength(0); i++)
{
for (int j = 0; j < xml.Cells.GetLength(1); j++)
{
if (this.Cells[i, j] == null) continue;
xml.Cells[i, j] = new CellStruct();
xml.Cells[i, j].Value = this.Cells[i, j].Value;
xml.Cells[i, j].Height = this.Cells[i, j].Height;
xml.Cells[i, j].Width = this.Cells[i, j].Width;
xml.Cells[i, j].RowIndex = this.Cells[i, j].RowIndex;
xml.Cells[i, j].RowSpan = this.Cells[i, j].RowSpan;
xml.Cells[i, j].ColumnIndex = this.Cells[i, j].ColumnIndex;
xml.Cells[i, j].ColumnSpan = this.Cells[i, j].ColumnSpan;
xml.Cells[i, j].Style = new CellStyle();
xml.Cells[i, j].Style.Bold = this.Cells[i, j].Style.Bold;
xml.Cells[i, j].Style.BorderWidth.LeftWdith = this.Cells[i, j].Style.BorderWidth.LeftWdith;
xml.Cells[i, j].Style.BorderWidth.TopWidth = this.Cells[i, j].Style.BorderWidth.TopWidth;
xml.Cells[i, j].Style.BorderWidth.RigthWidth = this.Cells[i, j].Style.BorderWidth.RigthWidth;
xml.Cells[i, j].Style.BorderWidth.BottomWidth = this.Cells[i, j].Style.BorderWidth.BottomWidth;
xml.Cells[i, j].Style.FontColor = this.Cells[i, j].Style.FontColor;
xml.Cells[i, j].Style.FontName = this.Cells[i, j].Style.FontName;
xml.Cells[i, j].Style.FontSize = this.Cells[i, j].Style.FontSize;
xml.Cells[i, j].Style.Format = this.Cells[i, j].Style.Format;
xml.Cells[i, j].Style.HorAlignment = this.Cells[i, j].Style.HorAlignment;
xml.Cells[i, j].Style.Italic = this.Cells[i, j].Style.Italic;
xml.Cells[i, j].Style.StyleName = this.Cells[i, j].Style.StyleName;
xml.Cells[i, j].Style.Underline = this.Cells[i, j].Style.Underline;
xml.Cells[i, j].Style.VerAligment = this.Cells[i, j].Style.VerAligment;
xml.Cells[i, j].Style.Number = this.Cells[i, j].Style.Number;
}
}
xml.ColumnsCount = this.ColumnsCount;
xml.ColumnsWidth = this.ColumnsWidth;
xml.DefaultHeight = this.DefaultHeight;
xml.DefaultWidth = this.DefaultWidth;
xml.RowsCount = this.RowsCount;
xml.RowsHeight = this.RowsHeight;
xml.PaperSizeIndex = this.PaperSizeIndex;
xml.PageMargins.Top = this.PageMargins.Top;
xml.PageMargins.Left = this.PageMargins.Left;
xml.PageMargins.Bottom = this.PageMargins.Bottom;
xml.PageMargins.Right = this.PageMargins.Right;
return xml;
}
/// <summary>
/// 初始化Excel格式的xml文档
/// </summary>
/// <param name="FileName">要打开的文档</param>
/// <param name="sheetName">要解析的工作簿名称</param>
public bool InitData(string FileName, string sheetName)
{
/// <summary>
/// 样式集合
/// </summary>
Hashtable m_StyleList = new Hashtable();
/// <summary>
/// 单元格对象集合
/// </summary>
CellStruct[,] m_Cells;
//用于表示列宽信息集合
Hashtable hash_columns = new Hashtable();
//打开文件
string sXml = FileName;
if (!System.IO.File.Exists(sXml))
return false;
System.Xml.XmlDocument xmlDoc = new System.Xml.XmlDocument();
xmlDoc.Load(sXml);
Debug.WriteLine(DateTime.Now.ToString());
XmlNodeList nodelist = xmlDoc.GetElementsByTagName("Worksheet");
System.Xml.XmlNode node = null;
for (int i = 0; i < nodelist.Count; i++)
{
if (xmlDoc.GetElementsByTagName("Worksheet").Item(i).Attributes["ss:Name"].Value.ToLower().Trim() == sheetName.ToLower().Trim())
{
node = xmlDoc.GetElementsByTagName("Worksheet").Item(i).ChildNodes[0];
}
}
if (node == null) return false;
//读取表格行数、列数、缺省列宽、缺省行高
XmlAttribute xmlAttrColumnsCount = node.Attributes["ss:ExpandedColumnCount"];
XmlAttribute xmlAttrRowsCount = node.Attributes["ss:ExpandedRowCount"];
XmlAttribute xmlAttrDefaultWidth = node.Attributes["ss:DefaultColumnWidth"];
XmlAttribute xmlAttrDefaultHeight = node.Attributes["ss:DefaultRowHeight"];
int ColumnsCount = Convert.ToInt32(xmlAttrColumnsCount.Value);
int RowsCount = Convert.ToInt32(xmlAttrRowsCount.Value);
m_ColumnsCount = ColumnsCount;
m_RowsCount = RowsCount;
double DefaultWidth = ExcelConvert.PointToPixels(Convert.ToDouble(xmlAttrDefaultWidth.Value));
double DefaultHeight = ExcelConvert.PointToPixels(Convert.ToDouble(xmlAttrDefaultHeight.Value));
m_DefaultWidth = DefaultWidth;
m_DefaultHeight = DefaultHeight;
//保存默认列宽信息
for (int l = 0; l < ColumnsCount; l++)
{
hash_columns[l] = DefaultWidth;
}
//创建二维数组存储单元格样式属性信息
m_Cells = new CellStruct[RowsCount, ColumnsCount];
//读取样式信息
m_StyleList = new Hashtable();
System.Xml.XmlNode stylenode = xmlDoc.GetElementsByTagName("Styles").Item(0).ChildNodes[0];
foreach (XmlNode style in xmlDoc.GetElementsByTagName("Styles").Item(0).ChildNodes)
{
CellStyle cs = new CellStyle();
//样式名称
string styleName = style.Attributes["ss:ID"].Value;
for (int k = 0; k < style.ChildNodes.Count; k++)
{
XmlNode nd = style.ChildNodes[k];
if (nd == null) continue;
switch (nd.Name)
{
case "Alignment": //对齐方式
if (nd.Attributes["ss:Horizontal"] != null && !string.IsNullOrEmpty(nd.Attributes["ss:Horizontal"].Value))
{
//水平对齐
string Horizontal = cs.FontName = nd.Attributes["ss:Horizontal"].Value;
Alignment ha = Horizontal == "Center" ? Alignment.Center : (Horizontal == "Left" ? Alignment.Left : Alignment.Right);
cs.HorAlignment = ha;
}
if (nd.Attributes["ss:Vertical"] != null && !string.IsNullOrEmpty(nd.Attributes["ss:Vertical"].Value))
{
//垂直对齐
string Vertical = cs.FontName = nd.Attributes["ss:Vertical"].Value;
Alignment va = Vertical == "Center" ? Alignment.Center : (Vertical == "Top" ? Alignment.Left : Alignment.Right);
cs.VerAligment = va;
}
break;
case "Borders": //边框样式
cs.BorderWidth = new GDIBorderWidth();
for (int l = 0; l < nd.ChildNodes.Count; l++)
{
XmlNode nw = nd.ChildNodes[l];
if (nw == null) continue;
if (nw.Attributes["ss:Weight"] == null)
continue;
string bd = nw.Attributes["ss:Weight"].Value;
switch (nw.Attributes["ss:Position"].Value)
{
case "Top":
cs.BorderWidth.TopWidth = Convert.ToByte(bd);
break;
case "Left":
cs.BorderWidth.LeftWdith = Convert.ToByte(bd);
break;
case "Right":
cs.BorderWidth.RigthWidth = Convert.ToByte(bd);
break;
case "Bottom":
cs.BorderWidth.BottomWidth = Convert.ToByte(bd);
break;
}
}
break;
case "Font": //字体
//字体名称
if (nd.Attributes["ss:FontName"] != null && !string.IsNullOrEmpty(nd.Attributes["ss:FontName"].Value))
cs.FontName = nd.Attributes["ss:FontName"].Value;
//字体样式
if (nd.Attributes["ss:Bold"] != null && !string.IsNullOrEmpty(nd.Attributes["ss:Bold"].Value))
cs.Bold = nd.Attributes["ss:Bold"].Value == "1";
if (nd.Attributes["ss:Italic"] != null && !string.IsNullOrEmpty(nd.Attributes["ss:Italic"].Value))
cs.Italic = nd.Attributes["ss:Italic"].Value == "1";
if (nd.Attributes["ss:Underline"] != null && !string.IsNullOrEmpty(nd.Attributes["ss:Underline"].Value))
cs.Underline = nd.Attributes["ss:Underline"].Value == "Single";
//字体大小
if (nd.Attributes["ss:Size"] != null && !string.IsNullOrEmpty(nd.Attributes["ss:Size"].Value))
cs.FontSize = nd.Attributes["ss:Size"].Value;
//字体颜色
if (nd.Attributes["ss:Color"] != null && !string.IsNullOrEmpty(nd.Attributes["ss:Color"].Value))
cs.FontColor = ExcelConvert.StringToColor(nd.Attributes["ss:Color"].Value);
break;
case "NumberFormat": //显示格式
string format = "";
//显示样式
if (nd.Attributes["ss:Format"] != null && !string.IsNullOrEmpty(nd.Attributes["ss:Format"].Value))
format = nd.Attributes["ss:Format"].Value;
if (format.Trim() == "Percent" || format.IndexOf("%") >= 0)
{ //百分比
cs.Format = CellDisplayType.PERCENT;
}
else if (format.IndexOf("¥") >= 0)
{ //货币
cs.Format = CellDisplayType.CURRENCURY;
}
else if (format.IndexOf("_") >= 0)
{ //数字
cs.Format = CellDisplayType.NUMBER;
cs.Number = (byte)(format.Trim().Length - 3);
if (cs.Number < 0) cs.Number = 2;
break;
}
else
{ //文本
cs.Format = CellDisplayType.STRING;
}
if (format == "") break;
//小数位数
string regexStr = @"[-+]?/b(?:[0-9]*/.)?[0-9]+/b";
MatchCollection mc = Regex.Matches(format, regexStr);
if (mc.Count > 0)
{
int num = mc[0].Value.Length - 2;
if (num <= 0)
{
num = 2;
}
cs.Number = (byte)num;
}
else
{
cs.Number = 2;
}
break;
}
}
cs.StyleName = styleName;
m_StyleList[styleName] = cs;
}
//读取数据信息
int RowIndex = 0; //当前行索引
int iRows = node.ChildNodes.Count;
int _columnIndex = 0;
for (int i = 0; i < iRows; i++)
{
XmlNode xmlRow = node.ChildNodes[i];
//读取列及列宽信息
if (xmlRow.Name == "Column")
{
//读取列索引信息
XmlAttribute xmlAttrColumnIndex = xmlRow.Attributes["ss:Index"];
if (xmlAttrColumnIndex != null && !String.IsNullOrEmpty(xmlAttrColumnIndex.Value))
{
_columnIndex = Convert.ToInt16(xmlAttrColumnIndex.Value) - 1;
}
//读取列宽信息
XmlAttribute xmlAttrColumnWidth = xmlRow.Attributes["ss:Width"];
if (xmlAttrColumnWidth != null && !String.IsNullOrEmpty(xmlAttrColumnWidth.Value))
{
double columnWidth = ExcelConvert.PointToPixels(Convert.ToDouble(xmlAttrColumnWidth.Value));
hash_columns[_columnIndex] = columnWidth;
}
_columnIndex++;
}
else if (xmlRow.Name == "Row")
{
int _rowHeight = (int)DefaultHeight;
//读取行高信息
XmlAttribute xmlRowHeight = xmlRow.Attributes["ss:Height"];
if (xmlRowHeight != null && !String.IsNullOrEmpty(xmlRowHeight.Value))
_rowHeight = (int)ExcelConvert.PointToPixels(Convert.ToDouble(xmlRowHeight.Value));
//存储行高
m_RowsHeight[RowIndex] = _rowHeight;
//逐行读取各单元格信息
int m_Cell_x = 0;
for (int j = 0; j < xmlRow.ChildNodes.Count; j++)
{
XmlNode xmlCell = xmlRow.ChildNodes[j];
//单元格值
string sText = "";
sText = xmlCell.InnerText;
//读取包含扩展列
int iRowSpan = 1;
XmlAttribute xmlAttrRowSpan = xmlCell.Attributes["ss:MergeDown"];
if (xmlAttrRowSpan != null && !String.IsNullOrEmpty(xmlAttrRowSpan.Value))
iRowSpan = Convert.ToInt32(xmlAttrRowSpan.Value) + 1;
//读取包含扩展行
int iColumnSpan = 1;
XmlAttribute xmlAttrColumnSpan = xmlCell.Attributes["ss:MergeAcross"];
if (xmlAttrColumnSpan != null && !String.IsNullOrEmpty(xmlAttrColumnSpan.Value))
iColumnSpan = Convert.ToInt32(xmlAttrColumnSpan.Value) + 1;
//读取单元格索引位置
int iIndex = m_Cell_x;
XmlAttribute xmlAttrIndex = xmlCell.Attributes["ss:Index"];
if (xmlAttrIndex != null && !String.IsNullOrEmpty(xmlAttrIndex.Value))
iIndex = Convert.ToInt32(xmlAttrIndex.Value);
//读取单元格样式ID
string StyleID = "Default";
XmlAttribute xmlAttrStyleID = xmlCell.Attributes["ss:StyleID"];
if (xmlAttrStyleID != null && !String.IsNullOrEmpty(xmlAttrStyleID.Value))
StyleID = xmlAttrStyleID.Value;
CellStyle cellStyle = (CellStyle)m_StyleList[StyleID];
//读取数据类型(非文本类型则右对齐)
if (xmlCell.ChildNodes.Count > 0)
{
XmlNode xmldata = xmlCell.ChildNodes[0];
XmlAttribute xmlAttrType = xmldata.Attributes["ss:Type"];
if (xmlAttrType != null && !String.IsNullOrEmpty(xmlAttrType.Value))
{
string dataType = xmlAttrType.Value;
if (dataType != "String" && cellStyle.HorAlignment == Alignment.None)
{
cellStyle.HorAlignment = Alignment.Right;
}
}
}
//将样式写入对象中...
CellStruct obj = new CellStruct();
obj.ColumnIndex = iIndex;
obj.RowIndex = RowIndex;
obj.Value = sText;
obj.Width = Convert.ToInt16(hash_columns[j]);
obj.Height = _rowHeight;
obj.RowSpan = iRowSpan;
obj.ColumnSpan = iColumnSpan;
obj.Style = cellStyle;
m_Cells[obj.RowIndex, obj.ColumnIndex] = obj;
Application.DoEvents();
//将列索引定位到下一个单元格
m_Cell_x += iColumnSpan;
}
RowIndex++;
}
}
m_ColumnsWidth = hash_columns;
Excel_Cells = m_Cells;
//读取打印及页面设置
node = node.ParentNode.ChildNodes[1];
ReadPageSettings(node);
return true;
}
/// <summary>
/// 读取页面设置
/// </summary>
private void ReadPageSettings(XmlNode node)
{
XmlNodeList nodelist = node.ChildNodes;
for (int i = 0; i < nodelist.Count; i++)
{
XmlNode nd = nodelist.Item(i);
switch (nd.Name.Trim())
{
case "PageSetup":
for (int l = 0; l < nd.ChildNodes.Count; l++)
{
//读取页边距
XmlNode npm = nd.ChildNodes[l];
if (npm == null) continue;
if (npm.Name.Trim() == "PageMargins")
{
double left = Convert.ToDouble(npm.Attributes["x:Left"].Value);
double top = Convert.ToDouble(npm.Attributes["x:Top"].Value);
double right = Convert.ToDouble(npm.Attributes["x:Right"].Value);
double bottom = Convert.ToDouble(npm.Attributes["x:Bottom"].Value);
m_PageMargins.Left = (int)(Math.Round(left * 96));
m_PageMargins.Top = (int)(Math.Round(top * 96));
m_PageMargins.Right = (int)(Math.Round(right * 96));
m_PageMargins.Bottom = (int)Math.Round((bottom * 96));
break;
}
}
break;
case "Print":
for (int l = 0; l < nd.ChildNodes.Count; l++)
{
//读取页面设置大小索引
XmlNode nps = nd.ChildNodes[l];
if (nps == null) continue;
if (nps.Name.Trim() == "PaperSizeIndex")
{
m_PaperSizeIndex = (int)Convert.ToDouble(nps.InnerText);
break;
}
}
break;
}
}
}
/// <summary>
/// 将Excel中的数据绘制成位图
/// </summary>
/// <param name="PosX"></param>
/// <param name="PosY"></param>
/// <returns></returns>
public Bitmap DrawExcelCells(int PosX, int PosY)
{
Bitmap bmp = new Bitmap((int)(GetWorkAreaWidth() + PosX * 2), ((int)GetWorkAreaHeight() + PosY * 2));
int currX = PosX;
int currY = PosY;
Graphics g = Graphics.FromImage(bmp);
g.CompositingQuality = System.Drawing.Drawing2D.CompositingQuality.HighQuality;
g.Clear(Color.White);
for (int i = 0; i < Excel_Cells.GetLength(0); i++)
{
for (int j = 0; j < Excel_Cells.GetLength(1); j++)
{
CellStruct cell = Excel_Cells[i, j];
if (cell == null) continue;
//高度
int height = 0;
for (int k = 0; k < cell.RowSpan; k++)
{
height += Convert.ToInt16(m_RowsHeight[k + i]);
}
//宽度
int width = 0;
for (int k = 0; k < cell.ColumnSpan; k++)
{
width += Convert.ToInt16(m_ColumnsWidth[k + j]);
}
//绘制边框
//左边框
if (cell.Style.BorderWidth.LeftWdith > 0)
g.DrawLine(new Pen(Color.Black, cell.Style.BorderWidth.LeftWdith),
new Point(currX, currY), new Point(currX, currY + height));
//上边框
if (cell.Style.BorderWidth.TopWidth > 0)
g.DrawLine(new Pen(Color.Black, cell.Style.BorderWidth.TopWidth),
new Point(currX, currY), new Point(currX + width, currY));
//右边框
if (cell.Style.BorderWidth.RigthWidth > 0)
g.DrawLine(new Pen(Color.Black, cell.Style.BorderWidth.RigthWidth),
new Point(currX + width, currY), new Point(currX + width, currY + height));
//下边框
if (cell.Style.BorderWidth.BottomWidth > 0)
g.DrawLine(new Pen(Color.Black, cell.Style.BorderWidth.BottomWidth),
new Point(currX, currY + height), new Point(currX + width, currY + height));
//绘制文字
string value = cell.Value;
//内容为空则继续下一个单元格
if (value.Trim() == "")
{
currX += width;
continue;
}
//设置并格式化打印文字内容
if (cell.Style.Format == CellDisplayType.CURRENCURY)
{
try { value = (double.Parse(value)).ToString("c" + cell.Style.Number); }
catch { }
}
else if (cell.Style.Format == CellDisplayType.PERCENT)
{
try { value = (double.Parse(value)).ToString("p" + cell.Style.Number); }
catch { }
}
else if (cell.Style.Format == CellDisplayType.NUMBER)
{
try { value = (double.Parse(value)).ToString("f" + cell.Style.Number); }
catch { }
}
//字体样式
Font font = new Font(cell.Style.FontName, float.Parse(cell.Style.FontSize));
if (cell.Style.Bold)
font = new Font(font, font.Style | FontStyle.Bold);
if (cell.Style.Italic)
font = new Font(font, font.Style | FontStyle.Italic);
if (cell.Style.Underline)
font = new Font(font, font.Style | FontStyle.Underline);
//打印文字区域计算
RectangleF rect = new RectangleF(currX + 2, currY + 2, width - 4, height - 4);
//根据水平对齐方式调整区域
if (cell.Style.HorAlignment == Alignment.Center)
{ rect = new RectangleF(rect.Left - 4, rect.Top, rect.Width + 8, rect.Height); }
else if (cell.Style.HorAlignment == Alignment.Right)
{ rect = new RectangleF(rect.Left - 4, rect.Top, rect.Width + 4, rect.Height); }
else { rect = new RectangleF(rect.Left, rect.Top, rect.Width + 4, rect.Height); }
//根据垂直对齐方式调整区域
SizeF fontsizeF = g.MeasureString(value, font);
if (rect.Height <= fontsizeF.Height + 2)
{
if (cell.Style.VerAligment == Alignment.Right)
{ rect = new RectangleF(rect.Left, rect.Top + rect.Height - fontsizeF.Height - 2, rect.Width, fontsizeF.Height + 2); }
else { rect = new RectangleF(rect.Left, rect.Top, rect.Width, fontsizeF.Height + 2); }
}
//打印格式
StringFormat sf = new StringFormat();
sf.Alignment = AlignmentToStringHAlignment(cell.Style.HorAlignment);
sf.LineAlignment = AlignmentToStringVAlignment(cell.Style.VerAligment); ;
sf.FormatFlags = StringFormatFlags.NoWrap; //不换行
//输出打印内容
g.DrawString(value, font, new SolidBrush(cell.Style.FontColor), rect, sf);
currX += width;
}
currX = PosX;
currY += Convert.ToInt16(m_RowsHeight[i]);
}
g.Dispose();
return bmp;
}
/// <summary>
/// 将数据显示在DataGridView中
/// </summary>
/// <param name="grid"></param>
public void DrawToGridView(DataGridView grid)
{
grid.Rows.Clear();
grid.RowCount = m_RowsCount;
grid.ColumnCount = m_ColumnsCount;
for (int k = 0; k < m_ColumnsCount; k++)
{
grid.Columns[k].Width = Convert.ToInt16(m_ColumnsWidth[k]);
}
for (int i = 0; i < Excel_Cells.GetLength(0); i++)
{
grid.Rows[i].Height = Convert.ToInt16(m_RowsHeight[i]);
for (int j = 0; j < Excel_Cells.GetLength(1); j++)
{
CellStruct cell = Excel_Cells[i, j];
if (cell == null) continue;
grid.Rows[i].Cells[cell.ColumnIndex].Value = cell.Value;
}
}
}
/// <summary>
/// 返回Excel工作区高度
/// </summary>
/// <returns></returns>
private int GetWorkAreaHeight()
{
int i = 0;
IDictionaryEnumerator ide = m_RowsHeight.GetEnumerator();
while (ide.MoveNext())
{
i += Convert.ToInt16(ide.Value);
}
return i;
}
/// <summary>
/// 将数据发送到打印机
/// </summary>
/// <param name="PosX"></param>
/// <param name="PosY"></param>
/// <param name="e"></param>
public void PrintExcelCells(int PosX, int PosY, System.Drawing.Printing.PrintPageEventArgs e)
{
int currX = PosX;
int currY = PosY;
Graphics g = e.Graphics;
for (int i = 0; i < Excel_Cells.GetLength(0); i++)
{
for (int j = 0; j < Excel_Cells.GetLength(1); j++)
{
CellStruct cell = Excel_Cells[i, j];
if (cell == null) continue;
//高度
int height = 0;
for (int k = 0; k < cell.RowSpan; k++)
{
height += Convert.ToInt16(m_RowsHeight[k + i]);
}
//宽度
int width = 0;
for (int k = 0; k < cell.ColumnSpan; k++)
{
width += Convert.ToInt16(m_ColumnsWidth[k + j]);
}
//绘制边框
//左边框
if (cell.Style.BorderWidth.LeftWdith > 0)
g.DrawLine(new Pen(Color.Black, cell.Style.BorderWidth.LeftWdith),
new Point(currX, currY), new Point(currX, currY + height));
//上边框
if (cell.Style.BorderWidth.TopWidth > 0)
g.DrawLine(new Pen(Color.Black, cell.Style.BorderWidth.TopWidth),
new Point(currX, currY), new Point(currX + width, currY));
//右边框
if (cell.Style.BorderWidth.RigthWidth > 0)
g.DrawLine(new Pen(Color.Black, cell.Style.BorderWidth.RigthWidth),
new Point(currX + width, currY), new Point(currX + width, currY + height));
//下边框
if (cell.Style.BorderWidth.BottomWidth > 0)
g.DrawLine(new Pen(Color.Black, cell.Style.BorderWidth.BottomWidth),
new Point(currX, currY + height), new Point(currX + width, currY + height));
//绘制文字
string value = cell.Value;
//内容为空则继续下一个单元格
if (value.Trim() == "")
{
currX += width;
continue;
}
//设置并格式化打印文字内容
if (cell.Style.Format == CellDisplayType.CURRENCURY)
{
try { value = (double.Parse(value)).ToString("c" + cell.Style.Number); }
catch { }
}
else if (cell.Style.Format == CellDisplayType.PERCENT)
{
try { value = (double.Parse(value)).ToString("p" + cell.Style.Number); }
catch { }
}
else if (cell.Style.Format == CellDisplayType.NUMBER)
{
try { value = (double.Parse(value)).ToString("f" + cell.Style.Number); }
catch { }
}
//字体样式
Font font = new Font(cell.Style.FontName, float.Parse(cell.Style.FontSize));
if (cell.Style.Bold)
font = new Font(font, font.Style | FontStyle.Bold);
if (cell.Style.Italic)
font = new Font(font, font.Style | FontStyle.Italic);
if (cell.Style.Underline)
font = new Font(font, font.Style | FontStyle.Underline);
//打印文字区域计算
RectangleF rect = new RectangleF(currX + 2, currY + 2, width - 4, height - 4);
//根据水平对齐方式调整区域
if (cell.Style.HorAlignment == Alignment.Center)
{ rect = new RectangleF(rect.Left - 4, rect.Top, rect.Width + 8, rect.Height); }
else if (cell.Style.HorAlignment == Alignment.Right)
{ rect = new RectangleF(rect.Left - 4, rect.Top, rect.Width + 4, rect.Height); }
else { rect = new RectangleF(rect.Left, rect.Top, rect.Width + 4, rect.Height); }
//根据垂直对齐方式调整区域
SizeF fontsizeF = g.MeasureString(value, font);
if (rect.Height <= fontsizeF.Height + 2)
{
if (cell.Style.VerAligment == Alignment.Right)
{ rect = new RectangleF(rect.Left, rect.Top + rect.Height - fontsizeF.Height - 2, rect.Width, fontsizeF.Height + 2); }
else { rect = new RectangleF(rect.Left, rect.Top, rect.Width, fontsizeF.Height + 2); }
}
//打印格式
StringFormat sf = new StringFormat();
sf.Alignment = AlignmentToStringHAlignment(cell.Style.HorAlignment);
sf.LineAlignment = AlignmentToStringVAlignment(cell.Style.VerAligment); ;
sf.FormatFlags = StringFormatFlags.NoWrap; //不换行
//输出打印内容
g.DrawString(value, font, new SolidBrush(cell.Style.FontColor), rect, sf);
currX += width;
}
currX = PosX;
currY += Convert.ToInt16(m_RowsHeight[i]);
}
}
/// <summary>
/// 返回Excel工作区宽度
/// </summary>
/// <returns></returns>
private int GetWorkAreaWidth()
{
int i = 0;
IDictionaryEnumerator ide = m_ColumnsWidth.GetEnumerator();
while (ide.MoveNext())
{
i += Convert.ToInt16(ide.Value);
}
return i;
}
/// <summary>
/// 对齐方式转换水平对齐方式
/// </summary>
/// <param name="value">要转换的值</param>
/// <returns></returns>
private StringAlignment AlignmentToStringHAlignment(Alignment value)
{
return (value == Alignment.Left || value == Alignment.None) ? StringAlignment.Near : value == Alignment.Center ? StringAlignment.Center : StringAlignment.Far;
}
/// <summary>
/// 对齐方式转换垂直对齐方式
/// </summary>
/// <param name="value">要转换的值</param>
/// <returns></returns>
private StringAlignment AlignmentToStringVAlignment(Alignment value)
{
return (value == Alignment.Left) ? StringAlignment.Near : (value == Alignment.Center || value == Alignment.None) ? StringAlignment.Center : StringAlignment.Far;
}
}