您的位置:首页 > 编程语言 > C#

C#读取写入excel单元格

2016-08-05 13:40 309 查看


c# 读取写入excel单元格(包括对excel的一些基本操作)

以下是一些对excel的一些基本操作

1:工程对excel类库的导入,如:c:\program files\Microsoft office\offiece11\excel.exe

2:命名控件的引入: using Microsoft.office.Interop.Excel;

3:如果是对一个已经存在的excel文件进行操作则:

Application app=new Application();

Workbook wbook=app.Workbooks.Open("c:\\temp.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,Type.missing,Type.missing);

Worksheet worksheet=(Worksheet)wbook.Worksheets[1];

4:如果是新建一个excel文件:

Application app=new Application();

Workbook wbook=app.Workbook.Add(Type.missing);

Worksheet worksheet=(Worksheet)wbook.Worksheets[1];

5:设置某个单元格里的内容:

worksheet.Cells[1,2]="列内容"

6读取某个单元格里的内容

string temp=((Range)worksheet.Cells[1,2]).Text;

7设置某个单元格里的格式

Excel.Range rtemp=worksheet.get_Range("A1","A1");

rtemp.Font.Name="宋体";

rtemp.Font.FontStyle="加粗";

rtemp.Font.Size=5;

8 保存新建的内容:

worksheet.SaveAs("c:\\temp.xls",Type.missing,Type.missing,Type.missing,Type.missing,Type.missing,Type.missing,Type.missing,Type.missing);

 

来自:http://www.cnblogs.com/farrell/archive/2008/01/24/1051273.html

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的时候,不弹出是否保存的窗口直接进行保存

=======================

获得range.MergeArea.Rows.Count合并的范围
内容来自用户分享和网络整理,不保证内容的准确性,如有侵权内容,可联系管理员处理 点击这里给我发消息
标签:  excel c#