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

c# 向Excel文件写入数据(Workbook 和Worksheet )

2009-12-24 16:29 525 查看
//注意:这个方法在服务器上运行时,服务器必须安装Office
//引用
using MyExcel=Microsoft.Office.Interop.Excel;
using System.Reflection;
public void DbExcel(string filepath,DataTable dt)
{
//打开excel模板
object missing =Missing.Value;
MyExcel.Application excelApp=new Microsoft.Office.Interop.Excel.Application();
excelApp.Application.Workbooks.Open(filepath, missing, missing, missing, missing, missing, missing, missing, missing, missing, missing, missing, missing, missing, missing);
//填充excel
MyExcel._Worksheet sheet = (MyExcel._Worksheet)excelApp.Worksheets[1];
//填充
if (dt.Rows.Count > 0)
{
int colCount = dt.Columns.Count;
object[,] dataArray = new object[dt.Rows.Count+1,colCount];
for (int i = 0; i < dt.Rows.Count; i++)
{
for (int j = 0; j < colCount; j++)
{
if (i == 0) {
//列名作为第一行
dataArray[i, j] = dt.Columns[j].ColumnName;
}
dataArray[i + 1, j] = dt.Rows[i][j];
}
}
MyExcel.Range myRange = sheet.get_Range(sheet.Cells[1,1], sheet.Cells[dt.Rows.Count+1,colCount]);
//添加数据
//内容体
myRange.Value2 = dataArray;
//设置头样式
//sheet.get_Range(sheet.Cells[1, 1], sheet.Cells[1, colCount]).Interior.ColorIndex = 7;
//设置样式
this.SetWorksheetStyle(sheet, dt.Rows.Count, colCount);

}
//刷新Pivot table等内容
excelApp.Workbooks[1].RefreshAll();
//保存excel文件
MyExcel.Workbook mybook = excelApp.Workbooks[1];
mybook.Save();
//关闭excel进程
mybook.Close(false, missing, missing);
//mybook = null;
excelApp.Quit();
//excelApp = null;
GC.Collect();
}
/// <summary>
/// 设置_Worksheet的样式
/// </summary>
/// <param name="sheet">Microsoft.Office.Interop.Excel._Worksheet对象</param>
/// <param name="rows">总行数</param>
/// <param name="columns">总列数</param>
public void SetWorksheetStyle(MyExcel._Worksheet sheet,int rows,int columns)
{
//设置头样式
sheet.get_Range(sheet.Cells[1, 1], sheet.Cells[1, columns]).Interior.ColorIndex = 7;
sheet.get_Range(sheet.Cells[1, 1], sheet.Cells[1, columns]).Font.Size =17;
sheet.get_Range(sheet.Cells[1, 1], sheet.Cells[1, columns]).Font.Bold=true;
//sheet.get_Range(sheet.Cells[1, 1], sheet.Cells[1, columns]).Font. = 7;
//列宽自动
sheet.get_Range(sheet.Cells[1, 1], sheet.Cells[1, columns]).EntireColumn.AutoFit();
//设置头的高度
MyExcel.Range range=(MyExcel.Range)sheet.Rows[(1).ToString(), System.Type.Missing];
range.RowHeight = 25;
sheet.get_Range(sheet.Cells[1, 4], sheet.Cells[rows, 4]).Font.Size = 27;
//表框
//sheet.get_Range(sheet.Cells[1, 4], sheet.Cells[rows, 4]).Borders.Weight = 4;
//sheet.get_Range(sheet.Cells[1, 4], sheet.Cells[rows, 4]).Borders.ThemeColor = 5;
}
内容来自用户分享和网络整理,不保证内容的准确性,如有侵权内容,可联系管理员处理 点击这里给我发消息
标签: