在用
Excel
作报表的时候,可能会碰到分页的情况,这样就要分成多个
Sheet
显示,如果要在每页都保留表头,就需要将第一页作为模板设计的表头部分拷贝到其他的
Sheet
上,这时就要用用到
Excel
中的单元格拷贝。
下面的代码说明如何一个
Sheet
上的选定内容拷贝到另一个
Sheet
上:
ThisApplication = new Excel.Application();
ThisWorkbook = ThisApplication.Workbooks.Open("z:\\Book1.xls", Type.Missing, Type.Missing, Type.Missing, Type.Missing, Type.Missing, Type.Missing, Type.Missing, Type.Missing, Type.Missing, Type.Missing, Type.Missing, Type.Missing);
ThisApplication.DisplayAlerts = false;
xlSheet = (Excel.Worksheet)ThisWorkbook.Worksheets.get_Item(1);
Excel.Range range = xlSheet.get_Range("A1", Type.Missing);
range.Value = "123";
Excel.Worksheet sheet1 = (Excel.Worksheet)ThisWorkbook.Worksheets.get_Item(2);
Excel.Range range1 = sheet1.get_Range("B1", Type.Missing);
range.Copy(range1);
ThisWorkbook.SaveAs("z:\\Book2.xls", Type.Missing, Type.Missing,
Type.Missing, Type.Missing, Type.Missing, Excel.XlSaveAsAccessMode.xlNoChange,
Type.Missing, Type.Missing, Type.Missing, Type.Missing);
可以看到,核心的代码是很简单的,就是选定一个源区域,然后指定另一个目标区域,调用源区域的
Copy
方法将内容整个复制到目标区域,但是你会发现是连单元格的格式等属性一并拷贝过去的,如果要只拷贝单元格中的文本呢?那就要用到
windows
剪贴板了:
xlSheet = (Excel.Worksheet)ThisWorkbook.Worksheets.get_Item(1);
Excel.Range range = xlSheet.get_Range("A1", Type.Missing);
range.Value = "123";
System.Windows.Forms.Clipboard.SetDataObject(range.Value.ToString());
Excel.Worksheet sheet1 = (Excel.Worksheet)ThisWorkbook.Worksheets.get_Item(2);
Excel.Range range1 = sheet1.get_Range("B1", Type.Missing);
sheet1.Paste(range1, false);
要注意的是,这种方式只能选一个单元格,复制一个,不能选定一批单元格进行复制。
上面的例子只给出了主要部分的代码,其他的像销毁
Excel
进程等操作请参考前面的几篇
Excel
作报表的随笔。
Trackback: http://tb.blog.csdn.net/TrackBack.aspx?PostId=1873962
在
Excel
中,行和列实际上仍然是
Range
,只不过取得行和列的方法和前面几篇随笔出现的有点不同,要使用
Worksheet
的
Rows
和
Columns
属性的
get_Item
方法,下面是例子代码,演示了怎样选中行,并且在行之间复制数据,和插入行:
ThisApplication = new Excel.Application();
ThisWorkbook = ThisApplication.Workbooks.Open("z:\\Book1.xls", Type.Missing, Type.Missing, Type.Missing, Type.Missing, Type.Missing, Type.Missing, Type.Missing, Type.Missing, Type.Missing, Type.Missing, Type.Missing, Type.Missing);
ThisApplication.DisplayAlerts = false;
xlSheet = (Excel.Worksheet)ThisWorkbook.Worksheets.get_Item(1);
//Excel.Range range = xlSheet.get_Range("G4",Type.Missing);
Excel.Range range = (Excel.Range)xlSheet.Rows.get_Item(18, Type.Missing);
Excel.Range range1 = (Excel.Range)xlSheet.Rows.get_Item(19, Type.Missing);
range.Value = "123";
range.Copy(range1);
range1.Rows.Insert(XlInsertShiftDirection.xlShiftDown);
ThisWorkbook.SaveAs("z:\\Book2.xls", Type.Missing, Type.Missing,
Type.Missing, Type.Missing, Type.Missing, Excel.XlSaveAsAccessMode.xlNoChange,
Type.Missing, Type.Missing, Type.Missing, Type.Missing);
Trackback: http://tb.blog.csdn.net/TrackBack.aspx?PostId=1873969
在用
Excel
作报表的时候,可能需要操作单元格的边框和填充颜色和纹理等操作,下面的代码说明如何设置选中的单元格的填充纹理和边框
try
{
ThisApplication = new Excel.Application();
ThisWorkbook = ThisApplication.Workbooks.Open("z:\\Book1.xls", Type.Missing, Type.Missing, Type.Missing, Type.Missing, Type.Missing, Type.Missing, Type.Missing, Type.Missing, Type.Missing, Type.Missing, Type.Missing, Type.Missing);
ThisApplication.DisplayAlerts = false;
xlSheet = (Excel.Worksheet)ThisWorkbook.Worksheets.get_Item(1);
Excel.Range range = xlSheet.get_Range("G4","H5");
range.Value = "123";
Excel.Style st = ThisWorkbook.Styles.Add("PropertyBorder", Type.Missing);
range.Interior.Pattern = Excel.XlPattern.xlPatternCrissCross;
range.Borders.Weight = 2;
range.Borders.get_Item(XlBordersIndex.xlEdgeRight).LineStyle = Excel.XlLineStyle.xlContinuous;
range.Borders.get_Item(XlBordersIndex.xlEdgeBottom).LineStyle = Excel.XlLineStyle.xlContinuous;
range.Borders.get_Item(XlBordersIndex.xlEdgeTop).LineStyle = Excel.XlLineStyle.xlContinuous;
range.Borders.get_Item(XlBordersIndex.xlDiagonalDown).LineStyle = Excel.XlLineStyle.xlLineStyleNone;
range.Borders.get_Item(XlBordersIndex.xlDiagonalUp).LineStyle = Excel.XlLineStyle.xlLineStyleNone;
range.Borders.get_Item(XlBordersIndex.xlInsideHorizontal).LineStyle = Excel.XlLineStyle.xlLineStyleNone;
range.Borders.get_Item(XlBordersIndex.xlInsideVertical).LineStyle = Excel.XlLineStyle.xlLineStyleNone;
range.Borders.get_Item(XlBordersIndex.xlEdgeLeft).LineStyle = Excel.XlLineStyle.xlDot;
range.Borders.get_Item(XlBordersIndex.xlEdgeLeft).Color = System.Drawing.ColorTranslator.ToOle(Color.Red);
ThisWorkbook.SaveAs("z:\\Book2.xls", Type.Missing, Type.Missing,
Type.Missing, Type.Missing, Type.Missing, Excel.XlSaveAsAccessMode.xlNoChange,
Type.Missing, Type.Missing, Type.Missing, Type.Missing);
}
catch
(Exception ex)
{
MessageBox.Show(ex.Message);
}
finally
{
ThisWorkbook.Close(Type.Missing, Type.Missing, Type.Missing);
ThisApplication.Workbooks.Close();
ThisApplication.Quit();
System.Runtime.InteropServices.Marshal.ReleaseComObject(ThisWorkbook);
System.Runtime.InteropServices.Marshal.ReleaseComObject(ThisApplication);
ThisWorkbook = null;
ThisApplication = null;
GC.Collect();
this.Close();
}
在Excel中,如果某个单元格的内容是数字,且比较长,默认情况下,会变为科学计数发表示,例如:123456789123456000会被表示为1.2345E+17,为了能够将数字按照普通的格式完全表示,就需要设置单元格的属性 ,下面是例子代码:
Excel.Application m_objExcel
=
null
;
Excel._Workbook m_objBook = null ;
Excel.Sheets m_objSheets = null ;
Excel._Worksheet m_objSheet = null ;
Excel.Range m_objRange = null ;
object m_objOpt = System.Reflection.Missing.Value;
try
{
m_objExcel = new Excel.Application();
m_objBook = m_objExcel.Workbooks.Open("e:\\1.xls", m_objOpt, m_objOpt, m_objOpt,
m_objOpt, m_objOpt, m_objOpt, m_objOpt, m_objOpt, m_objOpt, m_objOpt,
m_objOpt, m_objOpt, m_objOpt, m_objOpt);
m_objSheets = (Excel.Sheets)m_objBook.Worksheets;
m_objSheet = (Excel._Worksheet)(m_objSheets.get_Item(1));
m_objRange = m_objSheet.get_Range("A1", m_objOpt);
m_objRange.NumberFormatLocal = "#";
m_objBook.SaveAs("e:\\22.xls", m_objOpt, m_objOpt,
m_objOpt, m_objOpt, m_objOpt, Excel.XlSaveAsAccessMode.xlNoChange,
m_objOpt, m_objOpt, m_objOpt, m_objOpt, m_objOpt);
}
catch (Exception ex)
{
MessageBox.Show(ex.Message);
}
finally
{
m_objBook.Close(m_objOpt, m_objOpt, m_objOpt);
m_objExcel.Workbooks.Close();
m_objExcel.Quit();
System.Runtime.InteropServices.Marshal.ReleaseComObject(m_objBook);
System.Runtime.InteropServices.Marshal.ReleaseComObject(m_objExcel);
m_objBook = null;
m_objExcel = null;
GC.Collect();
}
Excel._Workbook m_objBook = null ;
Excel.Sheets m_objSheets = null ;
Excel._Worksheet m_objSheet = null ;
Excel.Range m_objRange = null ;
object m_objOpt = System.Reflection.Missing.Value;
try
{
m_objExcel = new Excel.Application();
m_objBook = m_objExcel.Workbooks.Open("e:\\1.xls", m_objOpt, m_objOpt, m_objOpt,
m_objOpt, m_objOpt, m_objOpt, m_objOpt, m_objOpt, m_objOpt, m_objOpt,
m_objOpt, m_objOpt, m_objOpt, m_objOpt);
m_objSheets = (Excel.Sheets)m_objBook.Worksheets;
m_objSheet = (Excel._Worksheet)(m_objSheets.get_Item(1));
m_objRange = m_objSheet.get_Range("A1", m_objOpt);
m_objRange.NumberFormatLocal = "#";
m_objBook.SaveAs("e:\\22.xls", m_objOpt, m_objOpt,
m_objOpt, m_objOpt, m_objOpt, Excel.XlSaveAsAccessMode.xlNoChange,
m_objOpt, m_objOpt, m_objOpt, m_objOpt, m_objOpt);
}
catch (Exception ex)
{
MessageBox.Show(ex.Message);
}
finally
{
m_objBook.Close(m_objOpt, m_objOpt, m_objOpt);
m_objExcel.Workbooks.Close();
m_objExcel.Quit();
System.Runtime.InteropServices.Marshal.ReleaseComObject(m_objBook);
System.Runtime.InteropServices.Marshal.ReleaseComObject(m_objExcel);
m_objBook = null;
m_objExcel = null;
GC.Collect();
}
本文演示一个简单的办法,并使用程序将一个dataset中的内容填充到指定的格子中,目的是尽可能的通用,从而避免C#代码必须知道Excel文件中字段和内容的位置的情况。
先制作一个简单的Excel文件作为模板,为了防止要填充的Cell中的内容和标题的内容一样,所以要填充内容的Cell中的内容是“$” + 字段名(要和DataTable中的列名一致),效果如图:
创建一个Winform程序,给窗体上添加两个按钮,代码分别为:
创建Xml:
private
void
button1_Click(
object
sender, EventArgs e)
{
DataColumn dcName = new DataColumn("name", typeof(string));
DataColumn dcAge = new DataColumn("age", typeof(int));
DataColumn dcMemo = new DataColumn("memo", typeof(string));
DataTable dt = new DataTable();
dt.Columns.Add(dcName);
dt.Columns.Add(dcAge);
dt.Columns.Add(dcMemo);
DataRow dr = dt.NewRow();
dr["name"] = "dahuzizyd";
dr["age"] = "20";
dr["memo"] = "dahuzizyd.cnblogs.com";
dt.Rows.Add(dr);
dt.AcceptChanges();
DataSet ds = new DataSet();
ds.Tables.Add(dt);
ds.WriteXml(Application.StartupPath +"\\ExcelBindingXml.xml");
}
{
DataColumn dcName = new DataColumn("name", typeof(string));
DataColumn dcAge = new DataColumn("age", typeof(int));
DataColumn dcMemo = new DataColumn("memo", typeof(string));
DataTable dt = new DataTable();
dt.Columns.Add(dcName);
dt.Columns.Add(dcAge);
dt.Columns.Add(dcMemo);
DataRow dr = dt.NewRow();
dr["name"] = "dahuzizyd";
dr["age"] = "20";
dr["memo"] = "dahuzizyd.cnblogs.com";
dt.Rows.Add(dr);
dt.AcceptChanges();
DataSet ds = new DataSet();
ds.Tables.Add(dt);
ds.WriteXml(Application.StartupPath +"\\ExcelBindingXml.xml");
}
提取xml并且加载到Excel模板上,再另存:
private
void
button2_Click(
object
sender, EventArgs e)
{
DataSet ds = new DataSet();
ds.ReadXml(Application.StartupPath + "\\ExcelBindingXml.xml");
Excel.Application m_objExcel = null;
Excel._Workbook m_objBook = null;
Excel.Sheets m_objSheets = null;
Excel._Worksheet m_objSheet = null;
Excel.Range m_objRange = null;
object m_objOpt = System.Reflection.Missing.Value;
try
{
m_objExcel = new Excel.Application();
m_objBook = m_objExcel.Workbooks.Open(Application.StartupPath + "\\ExcelTemplate.xls", m_objOpt, m_objOpt, m_objOpt, m_objOpt, m_objOpt, m_objOpt, m_objOpt, m_objOpt, m_objOpt, m_objOpt, m_objOpt, m_objOpt, m_objOpt, m_objOpt);
m_objSheets = (Excel.Sheets)m_objBook.Worksheets;
m_objSheet = (Excel._Worksheet)(m_objSheets.get_Item(1));
foreach (DataRow dr in ds.Tables[0].Rows)
{
for (int col = 0; col < ds.Tables[0].Columns.Count; col++)
{
for (int excelcol = 1; excelcol < 8; excelcol++)
{
for (int excelrow = 1; excelrow < 5; excelrow++)
{
string excelColName = ExcelColNumberToColText(excelcol);
m_objRange = m_objSheet.get_Range(excelColName + excelrow.ToString(), m_objOpt);
if ( m_objRange.Text.ToString().Replace("$","") == ds.Tables[0].Columns[col].ColumnName )
{
m_objRange.Value2 = dr[col].ToString();
}
}
}
}
}
m_objExcel.DisplayAlerts = false;
m_objBook.SaveAs(Application.StartupPath + "\\ExcelBindingXml.xls", m_objOpt, m_objOpt,
m_objOpt, m_objOpt, m_objOpt, Excel.XlSaveAsAccessMode.xlNoChange,
m_objOpt, m_objOpt, m_objOpt, m_objOpt, m_objOpt);
}
catch (Exception ex)
{
MessageBox.Show(ex.Message);
}
finally
{
m_objBook.Close(m_objOpt, m_objOpt, m_objOpt);
m_objExcel.Workbooks.Close();
m_objExcel.Quit();
System.Runtime.InteropServices.Marshal.ReleaseComObject(m_objBook);
System.Runtime.InteropServices.Marshal.ReleaseComObject(m_objExcel);
m_objBook = null;
m_objExcel = null;
GC.Collect();
}
}
{
DataSet ds = new DataSet();
ds.ReadXml(Application.StartupPath + "\\ExcelBindingXml.xml");
Excel.Application m_objExcel = null;
Excel._Workbook m_objBook = null;
Excel.Sheets m_objSheets = null;
Excel._Worksheet m_objSheet = null;
Excel.Range m_objRange = null;
object m_objOpt = System.Reflection.Missing.Value;
try
{
m_objExcel = new Excel.Application();
m_objBook = m_objExcel.Workbooks.Open(Application.StartupPath + "\\ExcelTemplate.xls", m_objOpt, m_objOpt, m_objOpt, m_objOpt, m_objOpt, m_objOpt, m_objOpt, m_objOpt, m_objOpt, m_objOpt, m_objOpt, m_objOpt, m_objOpt, m_objOpt);
m_objSheets = (Excel.Sheets)m_objBook.Worksheets;
m_objSheet = (Excel._Worksheet)(m_objSheets.get_Item(1));
foreach (DataRow dr in ds.Tables[0].Rows)
{
for (int col = 0; col < ds.Tables[0].Columns.Count; col++)
{
for (int excelcol = 1; excelcol < 8; excelcol++)
{
for (int excelrow = 1; excelrow < 5; excelrow++)
{
string excelColName = ExcelColNumberToColText(excelcol);
m_objRange = m_objSheet.get_Range(excelColName + excelrow.ToString(), m_objOpt);
if ( m_objRange.Text.ToString().Replace("$","") == ds.Tables[0].Columns[col].ColumnName )
{
m_objRange.Value2 = dr[col].ToString();
}
}
}
}
}
m_objExcel.DisplayAlerts = false;
m_objBook.SaveAs(Application.StartupPath + "\\ExcelBindingXml.xls", m_objOpt, m_objOpt,
m_objOpt, m_objOpt, m_objOpt, Excel.XlSaveAsAccessMode.xlNoChange,
m_objOpt, m_objOpt, m_objOpt, m_objOpt, m_objOpt);
}
catch (Exception ex)
{
MessageBox.Show(ex.Message);
}
finally
{
m_objBook.Close(m_objOpt, m_objOpt, m_objOpt);
m_objExcel.Workbooks.Close();
m_objExcel.Quit();
System.Runtime.InteropServices.Marshal.ReleaseComObject(m_objBook);
System.Runtime.InteropServices.Marshal.ReleaseComObject(m_objExcel);
m_objBook = null;
m_objExcel = null;
GC.Collect();
}
}
下面是一个辅助函数,主要是将整数的列序号转换到Excel用的以字母表示的列号,Excel最大列数为255。
private
string
ExcelColNumberToColText(
int
colNumber)
{
string colText = "";
int colTextLength = colNumber / 26;
int colTextLast = colNumber % 26;
if (colTextLast != 0)
{
switch (colTextLength)
{
case 0: break;
case 1: colText = "A"; break;
case 2: colText = "B"; break;
case 3: colText = "C"; break;
case 4: colText = "D"; break;
case 5: colText = "E"; break;
case 6: colText = "F"; break;
case 7: colText = "G"; break;
case 8: colText = "H"; break;
case 9: colText = "I"; break;
default: break;
}
}
else
{
switch (colTextLength)
{
case 1: colText = ""; break;
case 2: colText = "A"; break;
case 3: colText = "B"; break;
case 4: colText = "C"; break;
case 5: colText = "D"; break;
case 6: colText = "E"; break;
case 7: colText = "F"; break;
case 8: colText = "G"; break;
case 9: colText = "H"; break;
default: break;
}
}
switch (colTextLast)
{
case 0:colText = colText + "Z"; break;
case 1: colText = colText + "A"; break;
case 2: colText = colText + "B"; break;
case 3: colText = colText + "C"; break;
case 4: colText = colText + "D"; break;
case 5: colText = colText + "E"; break;
case 6: colText = colText + "F"; break;
case 7: colText = colText + "G"; break;
case 8: colText = colText + "H"; break;
case 9: colText = colText + "I"; break;
case 10: colText = colText + "J"; break;
case 11: colText = colText + "K"; break;
case 12: colText = colText + "L"; break;
case 13: colText = colText + "M"; break;
case 14: colText = colText + "N"; break;
case 15: colText = colText + "O"; break;
case 16: colText = colText + "P"; break;
case 17: colText = colText + "Q"; break;
case 18: colText = colText + "R"; break;
case 19: colText = colText + "S"; break;
case 20: colText = colText + "T"; break;
case 21: colText = colText + "U"; break;
case 22: colText = colText + "V"; break;
case 23: colText = colText + "W"; break;
case 24: colText = colText + "X"; break;
case 25: colText = colText + "Y"; break;
default: break;
}
return colText;
}
{
string colText = "";
int colTextLength = colNumber / 26;
int colTextLast = colNumber % 26;
if (colTextLast != 0)
{
switch (colTextLength)
{
case 0: break;
case 1: colText = "A"; break;
case 2: colText = "B"; break;
case 3: colText = "C"; break;
case 4: colText = "D"; break;
case 5: colText = "E"; break;
case 6: colText = "F"; break;
case 7: colText = "G"; break;
case 8: colText = "H"; break;
case 9: colText = "I"; break;
default: break;
}
}
else
{
switch (colTextLength)
{
case 1: colText = ""; break;
case 2: colText = "A"; break;
case 3: colText = "B"; break;
case 4: colText = "C"; break;
case 5: colText = "D"; break;
case 6: colText = "E"; break;
case 7: colText = "F"; break;
case 8: colText = "G"; break;
case 9: colText = "H"; break;
default: break;
}
}
switch (colTextLast)
{
case 0:colText = colText + "Z"; break;
case 1: colText = colText + "A"; break;
case 2: colText = colText + "B"; break;
case 3: colText = colText + "C"; break;
case 4: colText = colText + "D"; break;
case 5: colText = colText + "E"; break;
case 6: colText = colText + "F"; break;
case 7: colText = colText + "G"; break;
case 8: colText = colText + "H"; break;
case 9: colText = colText + "I"; break;
case 10: colText = colText + "J"; break;
case 11: colText = colText + "K"; break;
case 12: colText = colText + "L"; break;
case 13: colText = colText + "M"; break;
case 14: colText = colText + "N"; break;
case 15: colText = colText + "O"; break;
case 16: colText = colText + "P"; break;
case 17: colText = colText + "Q"; break;
case 18: colText = colText + "R"; break;
case 19: colText = colText + "S"; break;
case 20: colText = colText + "T"; break;
case 21: colText = colText + "U"; break;
case 22: colText = colText + "V"; break;
case 23: colText = colText + "W"; break;
case 24: colText = colText + "X"; break;
case 25: colText = colText + "Y"; break;
default: break;
}
return colText;
}
运行完成后,生成的Excel如下图: