日期:2014-05-17 浏览次数:20738 次
using System; using Microsoft.Office.Core; using Excel; namespace XingFuStudio.ExcelEdit { class ExcelEdit { string myFileName; Excel.Application myExcel; Excel.Workbook myWorkBook; /// <summary> /// 构造函数,不创建Excel工作薄 /// </summary> public ExcelEdit() { //请不要删除以下信息 //版权:http://XingFuStar.cnblogs.com } /// <summary> /// 创建Excel工作薄 /// </summary> public void CreateExcel() { myExcel = new Excel.Application(); myWorkBook = myExcel.Application.Workbooks.Add(true); } /// <summary> /// 显示Excel /// </summary> public void ShowExcel() { myExcel.Visible = true; } /// <summary> /// 将数据写入Excel /// </summary> /// <param name="data">要写入的二维数组数据</param> /// <param name="startRow">Excel中的起始行</param> /// <param name="startColumn">Excel中的起始列</param> public void WriteData(string[,] data, int startRow, int startColumn) { int rowNumber = data.GetLength(0); int columnNumber = data.GetLength(1); for (int i = 0; i < rowNumber; i++) { for (int j = 0; j < columnNumber; j++) { //在Excel中,如果某单元格以单引号“'”开头,表示该单元格为纯文本,因此,我们在每个单元格前面加单引号。 myExcel.Cells[startRow + i, startColumn + j] = "'" + data[i, j]; } } } /// <summary> /// 将数据写入Excel /// </summary> /// <param name="data">要写入的字符串</param> /// <param name="starRow">写入的行</param> /// <param name="startColumn">写入的列</param> public void WriteData(string data, int row, int column) { myExcel.Cells[row, column] = data; } /// <summary> /// 将数据写入Excel /// </summary> /// <param name="data">要写入的数据表</param> /// <param name="startRow">Excel中的起始行</param> /// <param name="startColumn">Excel中的起始列</param> public void WriteData(System.Data.DataTable data, int startRow, int startColumn) { for (int i = 0; i <= data.Rows.Count - 1; i++) { for (int j = 0; j <= data.Columns.Count - 1; j++) { //在Excel中,如果某单元格以单引号“'”开头,表示该单元格为纯文本,因此,我们在每个单元格前面加单引号。 myExcel.Cells[startRow + i, startColumn + j] = "'" + data.Rows[i][j].ToString(); } } } /// <summary> /// 读取指定单元格数据 /// </summary> /// <param name="row">行序号</param> /// <param name="column">列序号</param> /// <returns>该格的数据</returns> public string ReadData(int row, int column) { Excel.Range range = myExcel.get_Range(myExcel.Cells[row, column], myExcel.Cells[row, column]); return range.Text.ToString(); } /// <summary> /// 向Excel中插入图片 /// </summary> /// <param name="pictureName">图片的绝对路径加文件名</param> public void InsertPictures(string pictureName) { Excel.Worksheet worksheet = (Excel.Worksheet)myExcel.ActiveSheet; //后面的数字表示位置,位置默认 worksheet.Shapes.AddPicture(pictureName, MsoTriState.msoFalse, MsoTriState.msoTrue, 10, 10, 150, 150); } /// <summary> /// 向Excel中插入图片 /// </summary> /// <param name="pictureName">图片的绝对路径加文件名</param> /// <param name="left">左边距</param> /// <param name="to