C#中Excel表格操作

48 篇文章 1 订阅
19 篇文章 0 订阅

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];

}

}

}

range.NumberFormatLocal = "@"; //设置单元格格式为文本 range = (Range)worksheet.get_Range("A1", "E1"); //获取Excel多个单元格区域:本例做为Excel表头 range.Merge(0); //单元格合并动作 worksheet.Cells[1, 1] = "Excel单元格赋值"; //Excel单元格赋值 range.Font.Size = 15; //设置字体大小 range.Font.Underline=true; //设置字体是否有下划线 range.Font.Name="黑体"; 设置字体的种类 range.HorizontalAlignment=XlHAlign.xlHAlignCenter; //设置字体在单元格内的对其方式 range.ColumnWidth=15; //设置单元格的宽度 range.Cells.Interior.Color=System.Drawing.Color.FromArgb(255,204,153).ToArgb(); //设置单元格的背景色 range.Borders.LineStyle=1; //设置单元格边框的粗细 range.BorderAround(XlLineStyle.xlContinuous,XlBorderWeight.xlThick,XlColorIndex.xlColorIndexAutomatic,System.Drawing.Color.Black.ToArgb()); //给单元格加边框 range.Borders.get_Item(Microsoft.Office.Interop.Excel.XlBordersIndex.xlEdgeTop).LineStyle = Microsoft.Office.Interop.Excel.XlLineStyle.xlLineStyleNone; //设置单元格上边框为无边框 range.EntireColumn.AutoFit(); //自动调整列宽 Range.HorizontalAlignment= xlCenter; // 文本水平居方式 Range.VerticalAlignment= xlCenter //文本垂直居方式 Range.WrapText=true; //文本自动换行 Range.Interior.ColorIndex=39; //填充颜色为淡紫色 Range.Font.Color=clBlue; //字体颜色 xlsApp.DisplayAlerts=false; //保存Excel的时候,不弹出是否保存的窗口直接进行保存 ==================================================================== using System; using System.Collections.Generic; using System.Text; using System.Reflection; using System.Runtime.InteropServices; using Microsoft.Office.Interop.Excel; using ExcelApplication = Microsoft.Office.Interop.Excel.ApplicationClass; using System.IO; namespace ExcalDemo { public class ExcelFiles { public void CreateExcelFiles() { ExcelApplication excel = new ExcelApplication(); try { excel.Visible = false;// 不显示 Excel 文件,如果为 true 则显示 Excel 文件 excel.Workbooks.Add(Missing.Value);// 添加工作簿 Worksheet sheet = (Worksheet)excel.ActiveSheet;// 获取当前工作表 Range range = null;// 创建一个空的单元格对象 range = sheet.get_Range("A1", Missing.Value);// 获取单个单元格 range.RowHeight = 20; // 设置行高 range.ColumnWidth = 20; // 设置列宽 range.Borders.LineStyle = 1; // 设置单元格边框 range.Font.Bold = true; // 加粗字体 range.Font.Size = 20; // 设置字体大小 range.Font.ColorIndex = 5; // 设置字体颜色 range.Interior.ColorIndex = 6; // 设置单元格背景色 range.HorizontalAlignment = XlHAlign.xlHAlignCenter;// 设置单元格水平居 range.VerticalAlignment = XlVAlign.xlVAlignCenter;// 设置单元格垂直居 range.Value2 = "设置行高和列宽";// 设置单元格的值 range = sheet.get_Range("B2", "D4");// 获取多个单元格 range.Merge(Missing.Value); // 合并单元格 range.Columns.AutoFit(); // 设置列宽为自动适应 range.NumberFormatLocal = "#,##0.00";// 设置单元格格式为货币格式 // 设置单元格左边框加粗 range.Borders[XlBordersIndex.xlEdgeLeft].Weight = XlBorderWeight.xlThick; // 设置单元格右边框加粗 range.Borders[XlBordersIndex.xlEdgeRight].Weight = XlBorderWeight.xlThick; range.Value2 = "合并单元格"; // 页面设置 sheet.PageSetup.PaperSize = XlPaperSize.xlPaperA4; // 设置页面大小为A4 sheet.PageSetup.Orientation = XlPageOrientation.xlPortrait; // 设置垂直版面 sheet.PageSetup.HeaderMargin = 0.0; // 设置页眉边距 sheet.PageSetup.FooterMargin = 0.0; // 设置页脚边距 sheet.PageSetup.LeftMargin = excel.InchesToPoints(0.354330708661417); // 设置左边距 sheet.PageSetup.RightMargin = excel.InchesToPoints(0.354330708661417);// 设置右边距 sheet.PageSetup.TopMargin = excel.InchesToPoints(0.393700787401575); // 设置上边距 sheet.PageSetup.BottomMargin = excel.InchesToPoints(0.393700787401575);// 设置下边距 sheet.PageSetup.CenterHorizontally = true; // 设置水平居 // 打印文件 sheet.PrintOut(Missing.Value, Missing.Value, Missing.Value, Missing.Value, Missing.Value, Missing.Value, Missing.Value, Missing.Value); // 保存文件到程序运行目录下 sheet.SaveAs(Path.Combine(System.Windows.Forms.Application.StartupPath,"demo.xls"), Missing.Value, Missing.Value, Missing.Value, Missing.Value, Missing.Value, Missing.Value, Missing.Value, Missing.Value, Missing.Value); excel.ActiveWorkbook.Close(false, null, null); // 关闭 Excel 文件且不保存 } catch (Exception ex) { MessageBox.Show(ex.Message); } finally { excel.Quit(); // 退出 Excel excel = null; // 将 Excel 实例设置为空 } } } }
评论 1
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值