C#读取写入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);
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合并的范围

评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包

打赏作者

百老

你的鼓励将是我创作的最大动力

¥1 ¥2 ¥4 ¥6 ¥10 ¥20
扫码支付:¥1
获取中
扫码支付

您的余额不足,请更换扫码支付或充值

打赏作者

实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

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

余额充值