datatable生成excel和excel插入图片示例详解
Excel知识点
一、添加引用和命名空间
添加Microsoft.Office.Interop.Excel引用,它的默认路径是C:\ProgramFiles\MicrosoftVisualStudio9.0\VisualStudioToolsforOffice\PIA\Office12\Microsoft.Office.Interop.Excel.dll
代码中添加引用usingMicrosoft.Office.Interop.Excel;
二、Excel类的简单介绍
此命名空间下关于Excel类的结构分别为:
ApplicationClass-就是我们的excel应用程序。
Workbook-就是我们平常见的一个个excel文件,经常是使用Workbooks类对其进行操作。
Worksheet-就是excel文件中的一个个sheet页。
Worksheet.Cells[row,column]-就是某行某列的单元格,注意这里的下标row和column都是从1开始的,跟我平常用的数组或集合的下标有所不同。
知道了上述基本知识后,利用此类来操作excel就清晰了很多。
三、Excel的操作
任何操作Excel的动作首先肯定是用excel应用程序,首先要new一个ApplicationClass实例,并在最后将此实例释放。
ApplicationClassxlsApp=newApplicationClass();//1.创建Excel应用程序对象的一个实例,相当于我们从开始菜单打开Excel应用程序。
if(xlsApp==null)
{
//对此实例进行验证,如果为null则表示运行此代码的机器可能未安装Excel
}
1.打开现有的Excel文件
Workbookworkbook=xlsApp.Workbooks.Open(excelFilePath,Type.Missing,Type.Missing,Type.Missing,Type.Missing,Type.Missing,Type.Missing,Type.Missing,Type.Missing,Type.Missing,Type.Missing,Type.Missing,Type.Missing,Type.Missing,Type.Missing);
WorksheetmySheet=workbook.Sheets[1]asWorksheet;//第一个sheet页
mySheet.Name="testsheet";//这里修改sheet名称
2.复制sheet页
注意这里Copy方法的两个参数,指是的复制出来新的sheet页是在指定sheet页的前面还是后面,上面的例子就是指复制的sheet页在第一个sheet页的后面。 3.删除sheet页 4.选中sheet页 5.另存excel文件 6.释放excel资源 一般的我们传入一个DataTable生成Excel代码 如果要在excel中插入图片,我们需要把代码加入一行即可,如下所示 我们调用如下: 在Excel的指定位置加入图片 在Excel的指定位置加入文本框,和里面的内容. 我们可以这样来设计一个ExcelBase的基类: 先创建一个ExcelBE.cs: 接下来创建ExcelBase.cs: 调用的代码如下:
mySheet.Copy(Type.Missing,workbook.Sheets[1]);//复制mySheet成一个新的sheet页,复制完后的名称是mySheet页名称后加一个(2),这里就是testsheet(2),复制完后,Worksheet的数量增加一个
xlsApp.DisplayAlerts=false;//如果想删除某个sheet页,首先要将此项设为fasle。
(xlsApp.ActiveWorkbook.Sheets[1]asWorksheet).Delete();
(xlsApp.ActiveWorkbook.Sheets[1]asWorksheet).Select(Type.Missing);//选中某个sheet页
workbook.Saved=true;
workbook.SaveCopyAs(filepath);
workbook.Close(true,Type.Missing,Type.Missing);
workbook=null;
xlsApp.Quit();
xlsApp=null;
///<summary>
///
///</summary>
///<paramname="dt"></param>
protectedvoidExportExcel(DataTabledt)
{
if(dt==null||dt.Rows.Count==0)return;
Microsoft.Office.Interop.Excel.ApplicationxlApp=newMicrosoft.Office.Interop.Excel.Application();
if(xlApp==null)
{
return;
}
System.Globalization.CultureInfoCurrentCI=System.Threading.Thread.CurrentThread.CurrentCulture;
System.Threading.Thread.CurrentThread.CurrentCulture=newSystem.Globalization.CultureInfo("en-US");
Microsoft.Office.Interop.Excel.Workbooksworkbooks=xlApp.Workbooks;
Microsoft.Office.Interop.Excel.Workbookworkbook=workbooks.Add(Microsoft.Office.Interop.Excel.XlWBATemplate.xlWBATWorksheet);
Microsoft.Office.Interop.Excel.Worksheetworksheet=(Microsoft.Office.Interop.Excel.Worksheet)workbook.Worksheets[1];
Microsoft.Office.Interop.Excel.Rangerange;
longtotalCount=dt.Rows.Count;
longrowRead=0;
floatpercent=0;
for(inti=0;i<dt.Columns.Count;i++)
{
worksheet.Cells[1,i+1]=dt.Columns[i].ColumnName;
range=(Microsoft.Office.Interop.Excel.Range)worksheet.Cells[1,i+1];
range.Interior.ColorIndex=15;
range.Font.Bold=true;
}
for(intr=0;r<dt.Rows.Count;r++)
{
for(inti=0;i<dt.Columns.Count;i++)
{
worksheet.Cells[r+2,i+1]=dt.Rows[r][i].ToString();
}
rowRead++;
percent=((float)(100*rowRead))/totalCount;
}
xlApp.Visible=true;
}
protectedvoidExportExcel(DataTabledt)
{
if(dt==null||dt.Rows.Count==0)return;
Microsoft.Office.Interop.Excel.ApplicationxlApp=newMicrosoft.Office.Interop.Excel.Application();
if(xlApp==null)
{
return;
}
System.Globalization.CultureInfoCurrentCI=System.Threading.Thread.CurrentThread.CurrentCulture;
System.Threading.Thread.CurrentThread.CurrentCulture=newSystem.Globalization.CultureInfo("en-US");
Microsoft.Office.Interop.Excel.Workbooksworkbooks=xlApp.Workbooks;
Microsoft.Office.Interop.Excel.Workbookworkbook=workbooks.Add(Microsoft.Office.Interop.Excel.XlWBATemplate.xlWBATWorksheet);
Microsoft.Office.Interop.Excel.Worksheetworksheet=(Microsoft.Office.Interop.Excel.Worksheet)workbook.Worksheets[1];
Microsoft.Office.Interop.Excel.Rangerange;
longtotalCount=dt.Rows.Count;
longrowRead=0;
floatpercent=0;
for(inti=0;i<dt.Columns.Count;i++)
{
worksheet.Cells[1,i+1]=dt.Columns[i].ColumnName;
range=(Microsoft.Office.Interop.Excel.Range)worksheet.Cells[1,i+1];
range.Interior.ColorIndex=15;
}
for(intr=0;r<dt.Rows.Count;r++)
{
for(inti=0;i<dt.Columns.Count;i++)
{
try
{
worksheet.Cells[r+2,i+1]=dt.Rows[r][i].ToString();
}
catch
{
worksheet.Cells[r+2,i+1]=dt.Rows[r][i].ToString().Replace("=","");
}
}
rowRead++;
percent=((float)(100*rowRead))/totalCount;
}
worksheet.Shapes.AddPicture("C:\\Users\\spring\\Desktop\\1.gif",Microsoft.Office.Core.MsoTriState.msoFalse,Microsoft.Office.Core.MsoTriState.msoCTrue,100,200,200,300);
worksheet.Shapes.AddTextEffect(Microsoft.Office.Core.MsoPresetTextEffect.msoTextEffect1,"123456","Red",15,Microsoft.Office.Core.MsoTriState.msoFalse,Microsoft.Office.Core.MsoTriState.msoTrue,150,200);
xlApp.Visible=true;
}
publicvoidGenerateExcel()
{
DataTabledt=newDataTable();
dt.Columns.Add("Name",typeof(string));
dt.Columns.Add("Age",typeof(string));
DataRowdr=dt.NewRow();
dr["Name"]="spring";
dr["Age"]="20";
dt.Rows.Add(dr);
dt.AcceptChanges();
ExportExcel(dt);
}
worksheet.Shapes.AddPicture("C:\\Users\\spring\\Desktop\\1.gif",Microsoft.Office.Core.MsoTriState.msoFalse,Microsoft.Office.Core.MsoTriState.msoCTrue,100,200,200,300);
worksheet.Shapes.AddTextEffect(Microsoft.Office.Core.MsoPresetTextEffect.msoTextEffect1,"123456","Red",15,Microsoft.Office.Core.MsoTriState.msoFalse,Microsoft.Office.Core.MsoTriState.msoTrue,150,200);
publicclassExcelBE
{
privateint_row=0;
privateint_col=0;
privatestring_text=string.Empty;
privatestring_startCell=string.Empty;
privatestring_endCell=string.Empty;
privatestring_interiorColor=string.Empty;
privatebool_isMerge=false;
privateint_size=0;
privatestring_fontColor=string.Empty;
privatestring_format=string.Empty;
publicExcelBE(introw,intcol,stringtext,stringstartCell,stringendCell,stringinteriorColor,boolisMerge,intsize,stringfontColor,stringformat)
{
_row=row;
_col=col;
_text=text;
_startCell=startCell;
_endCell=endCell;
_interiorColor=interiorColor;
_isMerge=isMerge;
_size=size;
_fontColor=fontColor;
_format=format;
}
publicExcelBE()
{}
publicintRow
{
get{return_row;}
set{_row=value;}
}
publicintCol
{
get{return_col;}
set{_col=value;}
}
publicstringText
{
get{return_text;}
set{_text=value;}
}
publicstringStartCell
{
get{return_startCell;}
set{_startCell=value;}
}
publicstringEndCell
{
get{return_endCell;}
set{_endCell=value;}
}
publicstringInteriorColor
{
get{return_interiorColor;}
set{_interiorColor=value;}
}
publicboolIsMerge
{
get{return_isMerge;}
set{_isMerge=value;}
}
publicintSize
{
get{return_size;}
set{_size=value;}
}
publicstringFontColor
{
get{return_fontColor;}
set{_fontColor=value;}
}
publicstringFormart
{
get{return_format;}
set{_format=value;}
}
}
publicclassExcelBase
{
privateMicrosoft.Office.Interop.Excel.Applicationapp=null;
privateMicrosoft.Office.Interop.Excel.Workbookworkbook=null;
privateMicrosoft.Office.Interop.Excel.Worksheetworksheet=null;
privateMicrosoft.Office.Interop.Excel.RangeworkSheet_range=null;
publicExcelBase()
{
createDoc();
}
publicvoidcreateDoc()
{
try
{
app=newMicrosoft.Office.Interop.Excel.Application();
app.Visible=true;
workbook=app.Workbooks.Add(1);
worksheet=(Microsoft.Office.Interop.Excel.Worksheet)workbook.Sheets[1];
}
catch(Exceptione)
{
Console.Write("Error");
}
finally
{
}
}
publicvoidInsertData(ExcelBEbe)
{
worksheet.Cells[be.Row,be.Col]=be.Text;
workSheet_range=worksheet.get_Range(be.StartCell,be.EndCell);
workSheet_range.MergeCells=be.IsMerge;
workSheet_range.Interior.Color=GetColorValue(be.InteriorColor);
workSheet_range.Borders.Color=System.Drawing.Color.Black.ToArgb();
workSheet_range.ColumnWidth=be.Size;
workSheet_range.Font.Color=string.IsNullOrEmpty(be.FontColor)?System.Drawing.Color.White.ToArgb():System.Drawing.Color.Black.ToArgb();
workSheet_range.NumberFormat=be.Formart;
}
privateintGetColorValue(stringinteriorColor)
{
switch(interiorColor)
{
case"YELLOW":
returnSystem.Drawing.Color.Yellow.ToArgb();
case"GRAY":
returnSystem.Drawing.Color.Gray.ToArgb();
case"GAINSBORO":
returnSystem.Drawing.Color.Gainsboro.ToArgb();
case"Turquoise":
returnSystem.Drawing.Color.Turquoise.ToArgb();
case"PeachPuff":
returnSystem.Drawing.Color.PeachPuff.ToArgb();
default:
returnSystem.Drawing.Color.White.ToArgb();
}
}
}
privatevoidbtnRun_Click(objectsender,EventArgse)
{
ExcelBaseexcel=newExcelBase();
//createsthemainheader
ExcelBEbe=null;
be=newExcelBE(5,2,"TotalofProducts","B5","D5","YELLOW",true,10,"n",null);
excel.InsertData(be);
//createssubheaders
be=newExcelBE(6,2,"SoldProduct","B6","B6","GRAY",true,10,"",null);
excel.InsertData(be);
be=newExcelBE(6,3,"","C6","C6","GRAY",true,10,"",null);
excel.InsertData(be);
be=newExcelBE(6,4,"InitialTotal","D6","D6","GRAY",true,10,"",null);
excel.InsertData(be);
//addDatatocells
be=newExcelBE(7,2,"114287","B7","B7",null,false,10,"","#,##0");
excel.InsertData(be);
be=newExcelBE(7,3,"","C7","C7",null,false,10,"",null);
excel.InsertData(be);
be=newExcelBE(7,4,"129121","D7","D7",null,false,10,"","#,##0");
excel.InsertData(be);
//addpercentagerow
be=newExcelBE(8,2,"","B8","B8",null,false,10,"","");
excel.InsertData(be);
be=newExcelBE(8,3,"=B7/D7","C8","C8",null,false,10,"","0.0%");
excel.InsertData(be);
be=newExcelBE(8,4,"","D8","D8",null,false,10,"","");
excel.InsertData(be);
//addemptydivider
be=newExcelBE(9,2,"","B9","D9","GAINSBORO",true,10,"",null);
excel.InsertData(be);
}相关文章