C#中Excel表格操作

public void CreateExcel()

{

   int rowIndex=4;//行起始坐标

   int colIndex=1;//列起始坐标

   ApplicationClass myApp=null;

   Workbook myBook=null;

   Worksheet mySheet=null;

   //如果文件不存在,则将模板文件拷贝一份作为输出文件

   //这里如果通过File.Create来创建文件是不行的,因为xls

   //的空文件也有固定的格式,跟文本不一样的,也许有其它

   //通过程序直接生成excel的方法,大家可以尝试尝试的

   if(!File.Exists(outFilePath))

   {

    File.Copy(inputFilePath,outFilePath,true);

   }

   myApp= new ApplicationClass();

   myApp.Visible=false;

   object oMissiong=System.Reflection.Missing.Value;

   myApp.Workbooks.Open(outFilePath,oMissiong,oMissiong,oMissiong,oMissiong,

oMissiong,oMissiong,oMissiong,oMissiong,oMissiong,oMissiong,oMissiong,oMissiong);

   myBook=myApp.Workbooks[1];

   mySheet=(Worksheet)myBook.ActiveSheet;

   //

   //取得标题

   //

   foreach(DataColumn col in dv.Table.Columns)

   {

    colIndex++;

    mySheet.Cells[4,colIndex] = col.ColumnName;

    mySheet.get_Range(mySheet.Cells[4,colIndex],mySheet.Cells[4,colIndex]).HorizontalAlignment = XlVAlign.xlVAlignCenter;

//设置标题格式为居中对齐

   }

   //

   //取得表格中的数据

   //

   foreach(DataRowView row in dv)

   {

    rowIndex ++;

    colIndex = 1;

    foreach(DataColumn col in dv.Table.Columns)

    {

     colIndex ++;

     if(col.DataType == System.Type.GetType("System.DateTime"))

     {

      mySheet.Cells[rowIndex,colIndex] = (Convert.ToDateTime(row[col.ColumnName].ToString())).ToString("yyyy-MM-dd");

      mySheet.get_Range(mySheet.Cells[rowIndex,colIndex],mySheet.Cells[rowIndex,colIndex]).HorizontalAlignment = XlVAlign.xlVAlignCenter;//设置日期型的字段格式为居中对齐

     }

     else

      if(col.DataType == System.Type.GetType("System.String"))

     {

      mySheet.Cells[rowIndex,colIndex] = "'"+row[col.ColumnName].ToString();

      mySheet.get_Range(mySheet.Cells[rowIndex,colIndex],mySheet.Cells[rowIndex,colIndex]).HorizontalAlignment = XlVAlign.xlVAlignCenter;//设置字符型的字段格式为居中对齐

     }

     else

     {

      mySheet.Cells[rowIndex,colIndex] = row[col.ColumnName].ToString();

     }

    }

   }

   //

   //加载一个合计行

   //

   int rowSum = rowIndex + 1;

   int colSum = 2;

   mySheet.Cells[rowSum,2] = "合计";

   mySheet.get_Range(mySheet.Cells[rowSum,2],mySheet.Cells[rowSum,2]).HorizontalAlignment = XlHAlign.xlHAlignCenter;

   //

   //设置选中的部分的颜色

   //

   mySheet.get_Range(mySheet.Cells[rowSum,colSum],mySheet.Cells[rowSum,colIndex]).Select();

   mySheet.get_Range(mySheet.Cells[rowSum,colSum],mySheet.Cells[rowSum,colIndex]).Interior.ColorIndex = 19;//设置为浅黄色,共计有56种

   //

   //取得整个报表的标题

   //

   mySheet.Cells[2,2] = title;

   //

   //设置整个报表的标题格式

   //

   mySheet.get_Range(mySheet.Cells[2,2],mySheet.Cells[2,2]).Font.Bold = true;

   mySheet.get_Range(mySheet.Cells[2,2],mySheet.Cells[2,2]).Font.Size = 22;

   //

   //设置报表表格为最适应宽度

   //

   mySheet.get_Range(mySheet.Cells[4,2],mySheet.Cells[rowSum,colIndex]).Select();

   mySheet.get_Range(mySheet.Cells[4,2],mySheet.Cells[rowSum,colIndex]).Columns.AutoFit();

   //

   //设置整个报表的标题为跨列居中

   //

   mySheet.get_Range(mySheet.Cells[2,2],mySheet.Cells[2,colIndex]).Select();

   mySheet.get_Range(mySheet.Cells[2,2],mySheet.Cells[2,colIndex]).HorizontalAlignment = XlHAlign.xlHAlignCenterAcrossSelection;

   //

   //绘制边框

   //

   mySheet.get_Range(mySheet.Cells[4,2],mySheet.Cells[rowSum,colIndex]).Borders.LineStyle = 1;

   mySheet.get_Range(mySheet.Cells[4,2],mySheet.Cells[rowSum,2]).Borders[XlBordersIndex.xlEdgeLeft].Weight = XlBorderWeight.xlThick;//设置左边线加粗

   mySheet.get_Range(mySheet.Cells[4,2],mySheet.Cells[4,colIndex]).Borders[XlBordersIndex.xlEdgeTop].Weight = XlBorderWeight.xlThick;//设置上边线加粗

   mySheet.get_Range(mySheet.Cells[4,colIndex],mySheet.Cells[rowSum,colIndex]).Borders[XlBordersIndex.xlEdgeRight].Weight = XlBorderWeight.xlThick;//设置右边线加粗

   mySheet.get_Range(mySheet.Cells[rowSum,2],mySheet.Cells[rowSum,colIndex]).Borders[XlBordersIndex.xlEdgeBottom].Weight = XlBorderWeight.xlThick;//设置下边线加粗

   myBook.Save();;

   myBook.Close( true,outFilePath,true);

   System.Runtime.InteropServices.Marshal.ReleaseComObject(mySheet);

   System.Runtime.InteropServices.Marshal.ReleaseComObject(myBook);

   System.Runtime.InteropServices.Marshal.ReleaseComObject(myApp);

   GC.Collect();

}

==========================Excel操作类C#版的==========================

//引入Excel的COM组件

using System;

using System.Data;

using System.Configuration;

using System.Web;

using System.Web.Security;

using System.Web.UI;

using System.Web.UI.WebControls;

using System.Web.UI.WebControls.WebParts;

using System.Web.UI.HtmlControls;

using Microsoft.Office.Interop;

using Microsoft.Office.Core;

namespace ExcelEdit

{

/// <summary>

/// ExcelEdit 的摘要说明

/// </summary>

     public class ExcelEdit

     {

         public string mFilename;

         public Excel.Application app;

         public Excel.Workbooks wbs;

         public Excel.Workbook wb;

         public Excel.Worksheets wss;

         public Excel.Worksheet ws;

         public ExcelEdit()

         {

             //

             // TODO: 在此处添加构造函数逻辑

             //

         }

         public void Create()//创建一个Excel对象

         {

             app = new Excel.Application();

             wbs = app.Workbooks;

             wb = wbs.Add(true);

         }

         public void Open(string FileName)//打开一个Excel文件

         {

             app = new Excel.Application();

             wbs = app.Workbooks;

             wb = wbs.Add(FileName);

             //wb = wbs.Open(FileName,   0, true, 5,"", "", true, Excel.XlPlatform.xlWindows, "\t", false, false, 0, true,Type.Missing,Type.Missing);

             //wb = wbs.Open(FileName,Type.Missing,Type.Missing,Type.Missing,Type.Missing,Type.Missing,Type.Missing,Excel.XlPlatform.xlWindows,Type.Missing,Type.Missing,Type.Missing,Type.Missing,Type.Missing,Type.Missing,Type.Missing);

             mFilename = FileName;

         }

         public Excel.Worksheet GetSheet(string SheetName)//获取一个工作表

         {

             Excel.Worksheet s = (Excel.Worksheet)wb.Worksheets[SheetName];

             return s;

         }

         public Excel.Worksheet AddSheet(string SheetName)//添加一个工作表

         {

             Excel.Worksheet s = (Excel.Worksheet)wb.Worksheets.Add(Type.Missing,Type.Missing,Type.Missing,Type.Missing);

             s.Name = SheetName;

             return s;

         }

         public void DelSheet(string SheetName)//删除一个工作表

         {

             ((Excel.Worksheet)wb.Worksheets[SheetName]).Delete();

         }

         public Excel.Worksheet ReNameSheet(string OldSheetName, string NewSheetName)//重命名一个工作表一

         {

             Excel.Worksheet s = (Excel.Worksheet)wb.Worksheets[OldSheetName];

             s.Name = NewSheetName;

             return s;

         }

         public Excel.Worksheet ReNameSheet(Excel.Worksheet Sheet, string NewSheetName)//重命名一个工作表二

         {

             Sheet.Name = NewSheetName;

             return Sheet;

         }

         public void SetCellValue(Excel.Worksheet ws, int x, int y, object value)//ws:要设值的工作表      X行Y列      value    值

         {

             ws.Cells[x, y] = value;

         }

         public void SetCellValue(string ws, int x, int y, object value)//ws:要设值的工作表的名称 X行Y列 value 值

         {

             GetSheet(ws).Cells[x, y] = value;

         }

         public void SetCellProperty(Excel.Worksheet ws, int Startx, int Starty, int Endx, int Endy, int size, string name, Excel.Constants color, Excel.Constants HorizontalAlignment)//设置一个单元格的属性    字体,    大小,颜色    ,对齐方式

         {

             name = "宋体";

             size = 12;

             color = Excel.Constants.xlAutomatic;

             HorizontalAlignment = Excel.Constants.xlRight;

             ws.get_Range(ws.Cells[Startx, Starty], ws.Cells[Endx, Endy]).Font.Name = name;

             ws.get_Range(ws.Cells[Startx, Starty], ws.Cells[Endx, Endy]).Font.Size = size;

             ws.get_Range(ws.Cells[Startx, Starty], ws.Cells[Endx, Endy]).Font.Color = color;

             ws.get_Range(ws.Cells[Startx, Starty], ws.Cells[Endx, Endy]).HorizontalAlignment = HorizontalAlignment;

         }

         public void SetCellProperty(string wsn, int Startx, int Starty, int Endx, int Endy, int size, string name, Excel.Constants color, Excel.Constants HorizontalAlignment)

         {

             //name = "宋体";

             //size = 12;

             //color = Excel.Constants.xlAutomatic;

             //HorizontalAlignment = Excel.Constants.xlRight;

             Excel.Worksheet ws = GetSheet(wsn);

             ws.get_Range(ws.Cells[Startx, Starty], ws.Cells[Endx, Endy]).Font.Name = name;

             ws.get_Range(ws.Cells[Startx, Starty], ws.Cells[Endx, Endy]).Font.Size = size;

             ws.get_Range(ws.Cells[Startx, Starty], ws.Cells[Endx, Endy]).Font.Color = color;

             ws.get_Range(ws.Cells[Startx, Starty], ws.Cells[Endx, Endy]).HorizontalAlignment = HorizontalAlignment;

         }

         public void UniteCells(Excel.Worksheet ws, int x1, int y1, int x2, int y2)//合并单元格

         {

             ws.get_Range(ws.Cells[x1, y1], ws.Cells[x2, y2]).Merge(Type.Missing);

         }

         public void UniteCells(string ws, int x1, int y1, int x2, int y2)//合并单元格

         {

             GetSheet(ws).get_Range(GetSheet(ws).Cells[x1, y1], GetSheet(ws).Cells[x2, y2]).Merge(Type.Missing);

         }

         public void InsertTable(System.Data.DataTable dt, string ws, int startX, int startY)//将内存中数据表格插入到Excel指定工作表的指定位置 为在使用模板时控制格式时使用一

         {

             for (int i = 0; i <= dt.Rows.Count - 1; i++)

             {

                 for (int j = 0; j <= dt.Columns.Count - 1; j++)

                 {

                     GetSheet(ws).Cells[startX+i, j + startY] = dt.Rows[i][j].ToString();

                 }

             }

         }

         public void InsertTable(System.Data.DataTable dt, Excel.Worksheet ws, int startX, int startY)//将内存中数据表格插入到Excel指定工作表的指定位置二

         {

             for (int i = 0; i <= dt.Rows.Count - 1; i++)

             {

                 for (int j = 0; j <= dt.Columns.Count - 1; j++)

                 {

                     ws.Cells[startX+i, j + startY] = dt.Rows[i][j];

                 }

             }

         }

         public void AddTable(System.Data.DataTable dt, string ws, int startX, int startY)//将内存中数据表格添加到Excel指定工作表的指定位置一

         {

             for (int i = 0; i <= dt.Rows.Count - 1; i++)

             {

                 for (int j = 0; j <= dt.Columns.Count - 1; j++)

                 {

                     GetSheet(ws).Cells[i + startX, j + startY] = dt.Rows[i][j];

                 }

             }

         }

         public void AddTable(System.Data.DataTable dt, Excel.Worksheet ws, int startX, int startY)//将内存中数据表格添加到Excel指定工作表的指定位置二

         {

             for (int i = 0; i <= dt.Rows.Count - 1; i++)

             {

                 for (int j = 0; j <= dt.Columns.Count - 1; j++)

                 {

                     ws.Cells[i + startX, j + startY] = dt.Rows[i][j];

                 }

             }

         }

posted @ 2009-06-17 09:48  elegydance  阅读(3841)  评论(0编辑  收藏  举报