• 博客园logo
  • 会员
  • 周边
  • 新闻
  • 博问
  • 闪存
  • 赞助商
  • YouClaw
    • 搜索
      所有博客
    • 搜索
      当前博客
  • 写随笔 我的博客 短消息 简洁模式
    用户头像
    我的博客 我的园子 账号设置 会员中心 简洁模式 ... 退出登录
    注册 登录

五蕴

  • 博客园
  • 联系
  • 订阅
  • 管理

公告

View Post

C# 操作Excel

两种读取Excel方法

--------------------------------------------------------------------方法一

 

[html] view plaincopyprint?
  1.  /// <summary>  
  2.     /// 解析Excel,返回DataTable  
  3.     /// </summary>  
  4.     /// <param name="fileName"></param>  
  5.     /// <returns></returns>  
  6.     public static System.Data.DataTable ImpExcel(string fileName)  
  7.     {  
  8.       System.Data.DataTable dt = new System.Data.DataTable();  
  9.       try  
  10.       {  
  11.         Microsoft.Office.Interop.Excel.Application app;  
  12.         Workbooks wbs;  
  13.         Worksheet ws;  
  14.         app = new Microsoft.Office.Interop.Excel.Application();  
  15.         wbs = app.Workbooks;  
  16.         wbs.Add(fileName);  
  17.         ws = (Worksheet)app.Worksheets.get_Item(1);  
  18.         int a = ws.Rows.Count;  
  19.         int b = ws.Columns.Count;  
  20.         string name = ws.Name;  
  21.   
  22.           for (int i = 1; i <RowCount; i++)  
  23.           {  
  24.             DataRow dr = dt.NewRow();  
  25.             for (int j = 1; j <= ColumnsCount; j++)  
  26.             {  
  27.               Range range = ws.get_Range(app.Cells[i, j], app.Cells[i, j]);  
  28.               range.Select();  
  29.               dr[j - 1] = app.ActiveCell.Text.ToString();  
  30.             }  
  31.             dt.Rows.Add(dr);  
  32.            }  
  33.         KillProcess(app);  
  34.         return dt;  
  35.       }  
  36.       catch (Exception ex)  
  37.       {  
  38.         MessageBox.Show("数据绑定Excel失败! 失败原因:Excel格式不正确!", "提示信息", MessageBoxButtons.OK, MessageBoxIcon.Information);  
  39.         return dt;  
  40.       }  
  41.     }  
  42. <SPAN style="COLOR: #ff0000">-------------------------------------------<SPAN style="FONT-SIZE: 24px">方法二</SPAN></SPAN>  
  43.     /// <summary>  
  44.     /// 解析Excel,根据OleDbConnection直接连Excel  
  45.     /// </summary>  
  46.     /// <param name="filePath"></param>  
  47.     /// <param name="name"></param>  
  48.     /// <returns></returns>  
  49.     public static DataSet LoadDataFromExcel(string filePath, string name)  
  50.     {  
  51.       try  
  52.       {  
  53.         string strConn;  
  54.         //  strConn = " Provider = Microsoft.Jet.OLEDB.4.0 ; Data Source = " + filePath + ";Extended Properties=Excel 8.0";  
  55.         strConn = @"Provider=Microsoft.ACE.OLEDB.12.0;Data Source=" + filePath + ";Extended Properties=\"Excel 12.0 Xml;HDR=No\"";  
  56.        OleDbConnection OleConn = new OleDbConnection(strConn);  
  57.         OleConn.Open();  
  58.         string sql = "SELECT * FROM [" + name + "$]";//可是更改Sheet名称,比如sheet2,等等   
  59.         OleDbDataAdapter OleDaExcel = new OleDbDataAdapter(sql, OleConn);  
  60.         DataSet OleDsExcle = new DataSet();  
  61.         OleDaExcel.Fill(OleDsExcle, name);  
  62.         OleConn.Close();  
  63.         return OleDsExcle;  
  64.       }  
  65.       catch (Exception err)  
  66.       {  
  67.         MessageBox.Show("数据绑定Excel失败! 失败原因:" + err.Message, "提示信息", MessageBoxButtons.OK, MessageBoxIcon.Information);  
  68.         return null;  
  69.       }  
  70.     }  
 /// <summary>
    /// 解析Excel,返回DataTable
    /// </summary>
    /// <param name="fileName"></param>
    /// <returns></returns>
    public static System.Data.DataTable ImpExcel(string fileName)
    {
      System.Data.DataTable dt = new System.Data.DataTable();
      try
      {
        Microsoft.Office.Interop.Excel.Application app;
        Workbooks wbs;
        Worksheet ws;
        app = new Microsoft.Office.Interop.Excel.Application();
        wbs = app.Workbooks;
        wbs.Add(fileName);
        ws = (Worksheet)app.Worksheets.get_Item(1);
        int a = ws.Rows.Count;
        int b = ws.Columns.Count;
        string name = ws.Name;

          for (int i = 1; i <RowCount; i++)
          {
            DataRow dr = dt.NewRow();
            for (int j = 1; j <= ColumnsCount; j++)
            {
              Range range = ws.get_Range(app.Cells[i, j], app.Cells[i, j]);
              range.Select();
              dr[j - 1] = app.ActiveCell.Text.ToString();
            }
            dt.Rows.Add(dr);
           }
        KillProcess(app);
        return dt;
      }
      catch (Exception ex)
      {
        MessageBox.Show("数据绑定Excel失败! 失败原因:Excel格式不正确!", "提示信息", MessageBoxButtons.OK, MessageBoxIcon.Information);
        return dt;
      }
    }
-------------------------------------------方法二
    /// <summary>
    /// 解析Excel,根据OleDbConnection直接连Excel
    /// </summary>
    /// <param name="filePath"></param>
    /// <param name="name"></param>
    /// <returns></returns>
    public static DataSet LoadDataFromExcel(string filePath, string name)
    {
      try
      {
        string strConn;
        //  strConn = " Provider = Microsoft.Jet.OLEDB.4.0 ; Data Source = " + filePath + ";Extended Properties=Excel 8.0";
        strConn = @"Provider=Microsoft.ACE.OLEDB.12.0;Data Source=" + filePath + ";Extended Properties=\"Excel 12.0 Xml;HDR=No\"";
       OleDbConnection OleConn = new OleDbConnection(strConn);
        OleConn.Open();
        string sql = "SELECT * FROM [" + name + "$]";//可是更改Sheet名称,比如sheet2,等等 
        OleDbDataAdapter OleDaExcel = new OleDbDataAdapter(sql, OleConn);
        DataSet OleDsExcle = new DataSet();
        OleDaExcel.Fill(OleDsExcle, name);
        OleConn.Close();
        return OleDsExcle;
      }
      catch (Exception err)
      {
        MessageBox.Show("数据绑定Excel失败! 失败原因:" + err.Message, "提示信息", MessageBoxButtons.OK, MessageBoxIcon.Information);
        return null;
      }
    }

 

——————————————————插入Excel

 

[csharp] view plaincopyprint?
  1. /// <summary>   
  2.   /// 写入Excel文档   
  3.   /// </summary>   
  4.   /// <param name="Path">文件名称</param>   
  5.   public bool SaveFP2toExcel(string Path)  
  6.   {  
  7.    try  
  8.    {  
  9.     string strConn = "Provider=Microsoft.Jet.OLEDB.4.0;" +"Data Source="+ Path +";"+"Extended Properties=Excel 8.0;";  
  10.     OleDbConnection conn = new OleDbConnection(strConn);  
  11.     conn.Open();    
  12.     System.Data.OleDb.OleDbCommand cmd=new OleDbCommand ();  
  13.     cmd.Connection =conn;  
  14.     for(int i=0;i<fp2.Sheets [0].RowCount -1;i++)  
  15.     {  
  16.      if(fp2.Sheets [0].Cells[i,0].Text!="")  
  17.      {  
  18.       cmd.CommandText ="INSERT INTO [sheet1$] (工号,姓名,部门,职务,日期,时间) VALUES('"+fp2.Sheets [0].Cells[i,0].Text+ "','"+  
  19.        fp2.Sheets [0].Cells[i,1].Text+"','"+fp2.Sheets [0].Cells[i,2].Text+"','"+fp2.Sheets [0].Cells[i,3].Text+  
  20.        "','"+fp2.Sheets [0].Cells[i,4].Text+"','"+fp2.Sheets [0].Cells[i,5].Text+"')";  
  21.       cmd.ExecuteNonQuery ();  
  22.      }  
  23.     }  
  24.     conn.Close ();  
  25.     return true;  
  26.    }  
  27.    catch(System.Data.OleDb.OleDbException ex)  
  28.    {  
  29.     System.Diagnostics.Debug.WriteLine ("写入Excel发生错误:"+ex.Message );  
  30.    }  
  31.    return false;  
  32.   }  
/// <summary>
  /// 写入Excel文档
  /// </summary>
  /// <param name="Path">文件名称</param>
  public bool SaveFP2toExcel(string Path)
  {
   try
   {
    string strConn = "Provider=Microsoft.Jet.OLEDB.4.0;" +"Data Source="+ Path +";"+"Extended Properties=Excel 8.0;";
    OleDbConnection conn = new OleDbConnection(strConn);
    conn.Open();  
    System.Data.OleDb.OleDbCommand cmd=new OleDbCommand ();
    cmd.Connection =conn;
    for(int i=0;i<fp2.Sheets [0].RowCount -1;i++)
    {
     if(fp2.Sheets [0].Cells[i,0].Text!="")
     {
      cmd.CommandText ="INSERT INTO [sheet1$] (工号,姓名,部门,职务,日期,时间) VALUES('"+fp2.Sheets [0].Cells[i,0].Text+ "','"+
       fp2.Sheets [0].Cells[i,1].Text+"','"+fp2.Sheets [0].Cells[i,2].Text+"','"+fp2.Sheets [0].Cells[i,3].Text+
       "','"+fp2.Sheets [0].Cells[i,4].Text+"','"+fp2.Sheets [0].Cells[i,5].Text+"')";
      cmd.ExecuteNonQuery ();
     }
    }
    conn.Close ();
    return true;
   }
   catch(System.Data.OleDb.OleDbException ex)
   {
    System.Diagnostics.Debug.WriteLine ("写入Excel发生错误:"+ex.Message );
   }
   return false;
  }



 

新增、修改

 

[csharp] view plaincopyprint?
  1. string path="你的excel的路径";  
  2. workbook book=new workbook(path);  
  3. worksheet sheet=book["sheet3"];  
  4. sheet[行,列]=“你想存的值";  
  5. workbook.saveas(newpath);  
string path="你的excel的路径";
workbook book=new workbook(path);
worksheet sheet=book["sheet3"];
sheet[行,列]=“你想存的值";
workbook.saveas(newpath);

 

 

 

 

 

——————————————————修改Excel的值

 

 

[csharp] view plaincopyprint?
  1. 修改第一行Name的值为张三  
  2. string strComm = "update [Sheet1$] set Name='张三' WHERE 工号='132'";  
  3. OleDbConnection myConn = new OleDbConnection(strConn);  
  4. myConn.Open();  
  5. OleDbCommand com = new OleDbCommand(strComm, myConn);  
  6. com.ExecuteNonQuery();  
  7. myConn.Close();  
修改第一行Name的值为张三
string strComm = "update [Sheet1$] set Name='张三' WHERE 工号='132'";
OleDbConnection myConn = new OleDbConnection(strConn);
myConn.Open();
OleDbCommand com = new OleDbCommand(strComm, myConn);
com.ExecuteNonQuery();
myConn.Close();


------------------------------------------------导出————————————————————

 

 

[csharp] view plaincopyprint?
  1. using _Excel = Microsoft.Office.Interop.Excel;  
  2. using System.Drawing;  
  3. using System.Reflection;  
  4. using System.Windows.Forms;  
  5. using Microsoft.Office.Interop.Excel;  
  6.         /// <summary>   
  7.         /// DataTable直接导出Excel,此方法会把DataTable的数据用Excel打开,再自己手动去保存到确切的位置   
  8.         /// </summary>   
  9.         /// <param name="dt">要导出Excel的DataTable</param>   
  10.         /// <returns></returns>   
  11.         public static void ExportExcel(System.Data.DataTable table, string savePath, bool isExit)  
  12.         {  
  13.             if (!isExit)//保存路径是否存在   
  14.                 File.Copy(System.Windows.Forms.Application.StartupPath + @"\Excel\Excel.xls", savePath);  
  15.             _Excel.Application app = new _Excel.ApplicationClass();  
  16.             if (app == null)  
  17.             {  
  18.                 throw new Exception("Excel无法启动");  
  19.             }  
  20.             app.Visible = false;  
  21.             _Excel.Workbook book = app.Workbooks.Open(savePath, System.Type.Missing, System.Type.Missing, System.Type.Missing, System.Type.Missing, System.Type.Missing, System.Type.Missing, System.Type.Missing, System.Type.Missing, System.Type.Missing, System.Type.Missing, System.Type.Missing, System.Type.Missing, System.Type.Missing, System.Type.Missing);  
  22.             _Excel.Worksheet sheet = (_Excel.Worksheet)book.ActiveSheet;  
  23.   
  24.         for (int k = 1; k < ds.Tables[1].Rows.Count + 1; k++)  
  25.                 {  
  26.                     _Excel.Sheets xlSheets = book.Sheets as Sheets;  
  27.                     //  添加 Sheet   
  28.                     sheet = (Worksheet)xlSheets.Add(xlSheets[1], Type.Missing, Type.Missing, Type.Missing);  
  29.                 }  
  30.           for (int j = 1; j < ds.Tables[1].Rows.Count + 1; j++)  
  31.             {  
  32.      
  33.         _Excel.Range range = null;               
  34.                sheet = (_Excel.Worksheet)book.Sheets[j];          
  35.                if (!istrue)                  
  36.              sheet.Name ="123";            
  37.           else                  
  38.              sheet.Name = "345";  
  39.                 range = sheet.get_Range("A1", "C3");  
  40.                 range.MergeCells = true;//合并,将1-3行和1-3列合并为一个单元格   
  41.                 range.WrapText = true;  //自动换行   
  42.                 range.EntireRow.AutoFit();//行高根据内容自动调整   
  43.                 sheet.get_Range("A1", "C3").Borders[XlBordersIndex.xlEdgeBottom].LineStyle = BorderStyle.FixedSingle;//将1-3行和1-3列合并的单元格划下划线,根据[]内属性,可以设置文本上、下、左、右的的边框框   
  44.                 sheet.get_Range("A1", "C3").Borders.LineStyle = BorderStyle.FixedSingle;//给整个合并的单元格加上边框   
  45.                 sheet.get_Range("A1", "C3").Font.Name = "Times New Roman";//设置字体.   
  46.                  sheet.get_Range("A1", "C3").Font.Size = 22;//设置字体大小   
  47.                  range.Font.Bold = true;//加粗   
  48.                  range.RowHeight = 22;//调行高   
  49.                 rang.Interior.Color = System.Drawing.Color.FromArgb(255, 204, 153).ToArgb();//加背景色   
  50.                 range = sheet.get_Range(string.Format("D{0}", 1), string.Format("F{0}", 1));  
  51.                 range.MergeCells = true;//合并,将3-5列合并为一个单元格   
  52.                range.HorizontalAlignment = XlHAlign.xlHAlignCenter;//合并后文本水平居中   
  53.                 range.VerticalAlignment = XlVAlign.xlVAlignCenter;//合并后文本竖直居中    
  54.          單個sheet里求和:  
  55.         Excel.Range range2 = sheet.get_Range("B25", Type.Missing);  
  56.         range2.Formula = "=SUM(B2:B24)";  
  57.         range2.Calculate();  
  58.   
  59.   rang = (_Excel.Range)sheet.get_Range(string.Format("G{0}", 7), string.Format("G{0}", table.Rows.Count + 7));  
  60.   rang.NumberFormatLocal = "$#,##0.00"; //设置单元格格式为货币格式    
  61.         跨sheet求和:  
  62.         Excel.Worksheet wsheet1 = (Excel.Worksheet)excelSql.Worksheets.get_Item(1);  
  63.         Excel.Range range3 =wsheet1.get_Range("A23", Type.Missing);  
  64.         range3.Formula = "=Sheet3!B8+Sheet3!B12";  
  65.         range3.Calculate();  
  66.          sheet.Cells[1, 4] = ds.Tables[1].Rows[0]["FeightCode"].ToString();//给合并的列赋值   
  67.         //循环加载数据   
  68.          int startIndex = 0;  
  69.               for (int i = 0; i < ds.Tables[0].Rows.Count; i++)  
  70.                 {  
  71.                     if (ds.Tables[1].Rows[j - 1]["BoxCode"].ToString() == ds.Tables[0].Rows[i]["BoxCode"].ToString())  
  72.                     {  
  73.                     range = sheet.get_Range("b" + (15 + startIndex) + "", "e" + (15 + startIndex) + "");  
  74.                     range.MergeCells = true;  
  75.                     sheet.Cells[15 + startIndex, 2] = ds.Tables[0].Rows[i]["TypeName"].ToString();  
  76.                     range = (_Excel.Range)sheet.Cells[15 + startIndex, 2];  
  77.                     range.HorizontalAlignment = XlHAlign.xlHAlignCenter;  
  78.                     range.Font.Bold = true;  
  79.                     range.RowHeight = 22;  
  80.                     sheet.Cells[15 + startIndex, 6] = ds.Tables[0].Rows[i]["Qty"].ToString();  
  81.                     range = (_Excel.Range)sheet.Cells[15 + startIndex, 6];  
  82.                     range.HorizontalAlignment = XlHAlign.xlHAlignCenter;  
  83.                     range.Font.Bold = true;  
  84.                     range.RowHeight = 22;  
  85.                     sheet.Cells[15 + startIndex, 7] = ds.Tables[0].Rows[i]["UnitPrice"].ToString();  
  86.                     range = (_Excel.Range)sheet.Cells[15 + startIndex, 7];  
  87.                     range.HorizontalAlignment = XlHAlign.xlHAlignCenter;  
  88.                     range.Font.Bold = true;  
  89.                     range.RowHeight = 22;  
  90.                     sheet.Cells[15 + startIndex, 8] = ds.Tables[0].Rows[i]["Subtotal"].ToString();  
  91.                     range = (_Excel.Range)sheet.Cells[15 + startIndex, 8];  
  92.                     range.HorizontalAlignment = XlHAlign.xlHAlignCenter;  
  93.                     range.Font.Bold = true;  
  94.                     range.RowHeight = 22;  
  95.                      Image image = Picture.ReadPicture(ds.Tables[0].Rows[row][col].ToString());  
  96.                         range = sheet.get_Range(string.Format("A{0}", row * num + 29), string.Format("A{0}", row * num + 48));  
  97.                         sheet.Shapes.AddPicture(ds.Tables[0].Rows[row][col].ToString(), Microsoft.Office.Core.MsoTriState.msoFalse, Microsoft.Office.Core.MsoTriState.msoTrue, Convert.ToSingle(range.Left) + 15 + image.Width, Convert.ToSingle(range.Top) + 5, image.Width, image.Height);   //导出图片   
  98.                     range.EntireColumn.AutoFit();  
  99.                     System.Windows.Forms.Application.DoEvents();  
  100.                     startIndex++;  
  101.                     }  
  102.                 }  
using _Excel = Microsoft.Office.Interop.Excel;
using System.Drawing;
using System.Reflection;
using System.Windows.Forms;
using Microsoft.Office.Interop.Excel;
        /// <summary>
        /// DataTable直接导出Excel,此方法会把DataTable的数据用Excel打开,再自己手动去保存到确切的位置
        /// </summary>
        /// <param name="dt">要导出Excel的DataTable</param>
        /// <returns></returns>
        public static void ExportExcel(System.Data.DataTable table, string savePath, bool isExit)
        {
            if (!isExit)//保存路径是否存在
                File.Copy(System.Windows.Forms.Application.StartupPath + @"\Excel\Excel.xls", savePath);
            _Excel.Application app = new _Excel.ApplicationClass();
            if (app == null)
            {
                throw new Exception("Excel无法启动");
            }
            app.Visible = false;
            _Excel.Workbook book = app.Workbooks.Open(savePath, System.Type.Missing, System.Type.Missing, System.Type.Missing, System.Type.Missing, System.Type.Missing, System.Type.Missing, System.Type.Missing, System.Type.Missing, System.Type.Missing, System.Type.Missing, System.Type.Missing, System.Type.Missing, System.Type.Missing, System.Type.Missing);
            _Excel.Worksheet sheet = (_Excel.Worksheet)book.ActiveSheet;

        for (int k = 1; k < ds.Tables[1].Rows.Count + 1; k++)
                {
                    _Excel.Sheets xlSheets = book.Sheets as Sheets;
                    //  添加 Sheet
                    sheet = (Worksheet)xlSheets.Add(xlSheets[1], Type.Missing, Type.Missing, Type.Missing);
                }
          for (int j = 1; j < ds.Tables[1].Rows.Count + 1; j++)
            {
   
		_Excel.Range range = null;             
	           sheet = (_Excel.Worksheet)book.Sheets[j];        
               if (!istrue)                
	         sheet.Name ="123";          
	      else                
	         sheet.Name = "345";
                range = sheet.get_Range("A1", "C3");
                range.MergeCells = true;//合并,将1-3行和1-3列合并为一个单元格
                range.WrapText = true;  //自动换行
                range.EntireRow.AutoFit();//行高根据内容自动调整
                sheet.get_Range("A1", "C3").Borders[XlBordersIndex.xlEdgeBottom].LineStyle = BorderStyle.FixedSingle;//将1-3行和1-3列合并的单元格划下划线,根据[]内属性,可以设置文本上、下、左、右的的边框框
                sheet.get_Range("A1", "C3").Borders.LineStyle = BorderStyle.FixedSingle;//给整个合并的单元格加上边框
                sheet.get_Range("A1", "C3").Font.Name = "Times New Roman";//设置字体.
                 sheet.get_Range("A1", "C3").Font.Size = 22;//设置字体大小
                 range.Font.Bold = true;//加粗
                 range.RowHeight = 22;//调行高
                rang.Interior.Color = System.Drawing.Color.FromArgb(255, 204, 153).ToArgb();//加背景色
                range = sheet.get_Range(string.Format("D{0}", 1), string.Format("F{0}", 1));
                range.MergeCells = true;//合并,将3-5列合并为一个单元格
               range.HorizontalAlignment = XlHAlign.xlHAlignCenter;//合并后文本水平居中
                range.VerticalAlignment = XlVAlign.xlVAlignCenter;//合并后文本竖直居中 
		 單個sheet里求和:
		Excel.Range range2 = sheet.get_Range("B25", Type.Missing);
		range2.Formula = "=SUM(B2:B24)";
		range2.Calculate();

  rang = (_Excel.Range)sheet.get_Range(string.Format("G{0}", 7), string.Format("G{0}", table.Rows.Count + 7));
  rang.NumberFormatLocal = "$#,##0.00"; //设置单元格格式为货币格式 
		跨sheet求和:
		Excel.Worksheet wsheet1 = (Excel.Worksheet)excelSql.Worksheets.get_Item(1);
		Excel.Range range3 =wsheet1.get_Range("A23", Type.Missing);
		range3.Formula = "=Sheet3!B8+Sheet3!B12";
		range3.Calculate();
		 sheet.Cells[1, 4] = ds.Tables[1].Rows[0]["FeightCode"].ToString();//给合并的列赋值
		//循环加载数据
		 int startIndex = 0;
			  for (int i = 0; i < ds.Tables[0].Rows.Count; i++)
				{
				    if (ds.Tables[1].Rows[j - 1]["BoxCode"].ToString() == ds.Tables[0].Rows[i]["BoxCode"].ToString())
				    {
					range = sheet.get_Range("b" + (15 + startIndex) + "", "e" + (15 + startIndex) + "");
					range.MergeCells = true;
					sheet.Cells[15 + startIndex, 2] = ds.Tables[0].Rows[i]["TypeName"].ToString();
					range = (_Excel.Range)sheet.Cells[15 + startIndex, 2];
					range.HorizontalAlignment = XlHAlign.xlHAlignCenter;
					range.Font.Bold = true;
					range.RowHeight = 22;
					sheet.Cells[15 + startIndex, 6] = ds.Tables[0].Rows[i]["Qty"].ToString();
					range = (_Excel.Range)sheet.Cells[15 + startIndex, 6];
					range.HorizontalAlignment = XlHAlign.xlHAlignCenter;
					range.Font.Bold = true;
					range.RowHeight = 22;
					sheet.Cells[15 + startIndex, 7] = ds.Tables[0].Rows[i]["UnitPrice"].ToString();
					range = (_Excel.Range)sheet.Cells[15 + startIndex, 7];
					range.HorizontalAlignment = XlHAlign.xlHAlignCenter;
					range.Font.Bold = true;
					range.RowHeight = 22;
					sheet.Cells[15 + startIndex, 8] = ds.Tables[0].Rows[i]["Subtotal"].ToString();
					range = (_Excel.Range)sheet.Cells[15 + startIndex, 8];
					range.HorizontalAlignment = XlHAlign.xlHAlignCenter;
					range.Font.Bold = true;
					range.RowHeight = 22;
					 Image image = Picture.ReadPicture(ds.Tables[0].Rows[row][col].ToString());
						range = sheet.get_Range(string.Format("A{0}", row * num + 29), string.Format("A{0}", row * num + 48));
						sheet.Shapes.AddPicture(ds.Tables[0].Rows[row][col].ToString(), Microsoft.Office.Core.MsoTriState.msoFalse, Microsoft.Office.Core.MsoTriState.msoTrue, Convert.ToSingle(range.Left) + 15 + image.Width, Convert.ToSingle(range.Top) + 5, image.Width, image.Height);   //导出图片
					range.EntireColumn.AutoFit();
					System.Windows.Forms.Application.DoEvents();
					startIndex++;
				    }
				}
[csharp] view plaincopyprint?
  1.                  rang = sheet.get_Range("a" + (table.Rows.Count + 3) + "", "r" + (table.Rows.Count + 3) + "");  
  2.                  rang.Font.Bold = true;  
  3.                  rang.Interior.Color = System.Drawing.Color.FromArgb(255, 204, 153).ToArgb();//设置单元格背景颜色  
                 rang = sheet.get_Range("a" + (table.Rows.Count + 3) + "", "r" + (table.Rows.Count + 3) + "");
                 rang.Font.Bold = true;
                 rang.Interior.Color = System.Drawing.Color.FromArgb(255, 204, 153).ToArgb();//设置单元格背景颜色
[csharp] view plaincopyprint?
  1.    sheet.Columns.AutoFit();  
  2.    sheet.Cells.EntireColumn.AutoFit();  
  3.    sheet.Columns.EntireColumn.AutoFit();//列宽自适应。   
  4.    //  sheet.Cells.Borders.LineStyle =BorderStyle.Fixed3D;//设置边框   
  5. sheet = null;  
  6. book.Save();  
  7.    }  
  8.    book.Close(sheet, savePath, System.Type.Missing);  
  9.    app.Quit();  
  10.    app.DisplayAlerts=false;     //保存Excel的时候,不弹出是否保存的窗口直接进行保存   
  11.    System.GC.Collect();  
  12.    KillProcess(app);         
  13.   
  14.      /// <summary>   
  15.     /// 导出Excel后,杀死Excel进程   
  16.     /// </summary>   
  17.     /// <param name="app"></param>   
  18.     private static void KillProcess(_Excel.Application app)  
  19.     {  
  20.         IntPtr t = new IntPtr(app.Hwnd);  
  21.         int k = 0;  
  22.         GetWindowThreadProcessId(t, out k);  
  23.         System.Diagnostics.Process p = System.Diagnostics.Process.GetProcessById(k);  
  24.         p.Kill();  
  25.     }  
  26.     [DllImport("User32.dll", CharSet = CharSet.Auto)]  
  27.     public static extern int GetWindowThreadProcessId(IntPtr hwnd, out   int ID);  
			    sheet.Columns.AutoFit();
			    sheet.Cells.EntireColumn.AutoFit();
			    sheet.Columns.EntireColumn.AutoFit();//列宽自适应。
			    //  sheet.Cells.Borders.LineStyle =BorderStyle.Fixed3D;//设置边框
				sheet = null;
				book.Save();
			    }
			    book.Close(sheet, savePath, System.Type.Missing);
			    app.Quit();
			    app.DisplayAlerts=false;     //保存Excel的时候,不弹出是否保存的窗口直接进行保存
			    System.GC.Collect();
			    KillProcess(app);       
 
         /// <summary>
        /// 导出Excel后,杀死Excel进程
        /// </summary>
        /// <param name="app"></param>
        private static void KillProcess(_Excel.Application app)
        {
            IntPtr t = new IntPtr(app.Hwnd);
            int k = 0;
            GetWindowThreadProcessId(t, out k);
            System.Diagnostics.Process p = System.Diagnostics.Process.GetProcessById(k);
            p.Kill();
        }
        [DllImport("User32.dll", CharSet = CharSet.Auto)]
        public static extern int GetWindowThreadProcessId(IntPtr hwnd, out   int ID);


C#导出写保护的Excel,设置某些区域可以编辑
       对Excel操作时,由于使用权限的不同,可能对表格的操作权限也不一样。EXCEL提供了保护工作表以及允许编辑单元格功能。相应的在C#中就可以对Excel表格进行操作。
有两种方法可以实现:
第一种:

[csharp] view plaincopyprint?
  1. 主要用Protect()方法保护工作表,Worksheet.Protection.AllowEditRanges设置允许编辑的单元格。  
  2. public void CreateExcel()  
  3.     {  
  4.         //创建一个Excel文件   
  5.         Microsoft.Office.Interop.Excel.Application myExcel = new Microsoft.Office.Interop.Excel.Application();  
  6.         Microsoft.Office.Interop.Excel.Workbook excelWorkbook = null;  
  7.         Microsoft.Office.Interop.Excel.Worksheet excelSheet = null;  
  8.         myExcel.Application.Workbooks.Add(true);  
  9.         //让Excel文件可见   
  10.         myExcel.Visible = true;  
  11.         myExcel.Cells[1, 4] = "普通报表";  
  12.         //逐行写入数据   
  13.         for (int i = 0; i < 11; i++)  
  14.         {  
  15.             for (int j = 0; j < 7; j++)  
  16.             {  
  17.                 //以单引号开头,表示该单元格为纯文本   
  18.                 myExcel.Cells[2 + i, 1 + j] = "'" + i;  
  19.             }  
  20.         }  
  21.         try  
  22.         {  
  23.             string excelTemp ="c:\\a.xls";         
  24.             //excelWorkbook = myExcel.Workbooks[1];   
  25.             excelWorkbook = myExcel.ActiveWorkbook;  
  26.             excelSheet = (Microsoft.Office.Interop.Excel.Worksheet)excelWorkbook.ActiveSheet;  
  27.               
  28.             //设定允许操作的单元格   
  29.             Microsoft.Office.Interop.Excel.AllowEditRanges ranges = excelSheet.Protection.AllowEditRanges;  
  30.             ranges.Add("Information",  myExcel.Application.get_Range("B2", "B2"),  Type.Missing);  
  31.             //保护工作表   
  32.             excelSheet.Protect("MyPassword", Type.Missing, Type.Missing, Type.Missing,  
  33.               Type.Missing, Type.Missing, Type.Missing, Type.Missing,  
  34.              Type.Missing, Type.Missing, Type.Missing, Type.Missing,  
  35.               Type.Missing, true, Type.Missing, Type.Missing);  
  36.             //Realease the com object   
  37.             System.Runtime.InteropServices.Marshal.ReleaseComObject(excelSheet);  
  38.             excelSheet = null;  
  39.   
  40.             //Save the result to a temp path   
  41.             excelWorkbook.SaveAs(excelTemp, Excel.XlFileFormat.xlWorkbookNormal,  null, null, false, false,  
  42.                                  Microsoft.Office.Interop.Excel.XlSaveAsAccessMode.xlNoChange, Type.Missing,  
  43.                                  Type.Missing, Type.Missing,Type.Missing,Type.Missing);  
  44.         }  
  45.         catch (Exception ex)  
  46.         {  
  47.             throw;  
  48.         }  
  49.         finally  
  50.         {  
  51.             if (excelWorkbook != null)  
  52.             {  
  53.                 System.Runtime.InteropServices.Marshal.ReleaseComObject(excelWorkbook);  
  54.                 excelWorkbook = null;  
  55.             }  
  56.             if (myExcel != null)  
  57.             {  
  58.                 myExcel.Workbooks.Close();  
  59.                 myExcel.Quit();  
  60.                 System.Runtime.InteropServices.Marshal.ReleaseComObject(myExcel);  
  61.                 myExcel = null;  
  62.             }  
  63.             GC.Collect();  
  64.         }  
  65.     }  
  66.  PS:借用此方法我写了个循环来设定单元格保护,没想到一直在报HRESULT:0x800A03EC 的一个异常,郁闷。  
  67.         经过一番折腾,发现 AllowEditRanges.Add方法的第一个参数名是不能够重复的,写循环的时候没注意。   
主要用Protect()方法保护工作表,Worksheet.Protection.AllowEditRanges设置允许编辑的单元格。
public void CreateExcel()
    {
        //创建一个Excel文件
        Microsoft.Office.Interop.Excel.Application myExcel = new Microsoft.Office.Interop.Excel.Application();
        Microsoft.Office.Interop.Excel.Workbook excelWorkbook = null;
        Microsoft.Office.Interop.Excel.Worksheet excelSheet = null;
        myExcel.Application.Workbooks.Add(true);
        //让Excel文件可见
        myExcel.Visible = true;
        myExcel.Cells[1, 4] = "普通报表";
        //逐行写入数据
        for (int i = 0; i < 11; i++)
        {
            for (int j = 0; j < 7; j++)
            {
                //以单引号开头,表示该单元格为纯文本
                myExcel.Cells[2 + i, 1 + j] = "'" + i;
            }
        }
        try
        {
            string excelTemp ="c:\\a.xls";       
            //excelWorkbook = myExcel.Workbooks[1];
            excelWorkbook = myExcel.ActiveWorkbook;
            excelSheet = (Microsoft.Office.Interop.Excel.Worksheet)excelWorkbook.ActiveSheet;
            
            //设定允许操作的单元格
            Microsoft.Office.Interop.Excel.AllowEditRanges ranges = excelSheet.Protection.AllowEditRanges;
            ranges.Add("Information",  myExcel.Application.get_Range("B2", "B2"),  Type.Missing);
            //保护工作表
            excelSheet.Protect("MyPassword", Type.Missing, Type.Missing, Type.Missing,
              Type.Missing, Type.Missing, Type.Missing, Type.Missing,
             Type.Missing, Type.Missing, Type.Missing, Type.Missing,
              Type.Missing, true, Type.Missing, Type.Missing);
            //Realease the com object
            System.Runtime.InteropServices.Marshal.ReleaseComObject(excelSheet);
            excelSheet = null;

            //Save the result to a temp path
            excelWorkbook.SaveAs(excelTemp, Excel.XlFileFormat.xlWorkbookNormal,  null, null, false, false,
                                 Microsoft.Office.Interop.Excel.XlSaveAsAccessMode.xlNoChange, Type.Missing,
                                 Type.Missing, Type.Missing,Type.Missing,Type.Missing);
        }
        catch (Exception ex)
        {
            throw;
        }
        finally
        {
            if (excelWorkbook != null)
            {
                System.Runtime.InteropServices.Marshal.ReleaseComObject(excelWorkbook);
                excelWorkbook = null;
            }
            if (myExcel != null)
            {
                myExcel.Workbooks.Close();
                myExcel.Quit();
                System.Runtime.InteropServices.Marshal.ReleaseComObject(myExcel);
                myExcel = null;
            }
            GC.Collect();
        }
    }
 PS:借用此方法我写了个循环来设定单元格保护,没想到一直在报HRESULT:0x800A03EC 的一个异常,郁闷。
        经过一番折腾,发现 AllowEditRanges.Add方法的第一个参数名是不能够重复的,写循环的时候没注意。 


第二种:
用locked属性,设置Locked = false 的区域就可编辑的区域

 

 

[csharp] view plaincopyprint?
  1. worksheet.get_Range(worksheet.Cells[1, 1], worksheet.Cells[10, 10]).Locked = false;  
  2.    //保护工作表   
  3.   worksheet.Protect("MyPassword", Type.Missing, Type.Missing, Type.Missing,  
  4.            Type.Missing, Type.Missing, Type.Missing, Type.Missing,  
  5.            Type.Missing, Type.Missing, Type.Missing, Type.Missing,  
  6.            Type.Missing, true, true, true);  
  7.   
  8.   
  9.   ///        
  10.       ///   在工作表中插入行,并调整其他行以留出空间      
  11.       ///        
  12.       ///        
  13.   当前工作表     
  14.       ///        
  15.   欲插入的行索引     
  16.       private   void   InsertRows(Excel.Worksheet   sheet,   int   rowIndex)     
  17.       {     
  18.         range   =   (Excel.Range)sheet.Rows[rowIndex,   missing];           
  19.         //object   Range.Insert(object   shift,   object   copyorigin);        
  20.         //shift:   Variant类型,可选。指定单元格的调整方式。可以为下列   XlInsertShiftDirection   常量之一:      
  21.         //xlShiftToRight   或   xlShiftDown。如果省略该参数,Microsoft   Excel   将根据区域形状确定调整方式。      
  22.         range.Insert(Excel.XlInsertShiftDirection.xlShiftDown,   missing);         
  23.       }     
  24.       
  25.       ///        
  26.       ///   在工作表中删除行      
  27.       ///        
  28.       ///        
  29.   当前工作表     
  30.       ///        
  31.   欲删除的行索引     
  32.       private   void   DeleteRows(Excel.Worksheet   sheet,   int   rowIndex)     
  33.       {     
  34.         range   =   (Range)sheet.Rows[rowIndex,   missing];     
  35.         range.Delete(Excel.XlDeleteShiftDirection.xlShiftUp);     
  36.       }     
  37.       
  38.       ///        
  39.       ///   退出Excel,并且释放调用的COM资源      
  40.       ///        
  41.       private   void   Dispose()     
  42.       {     
  43.         book.Close(missing,   missing,   missing);     
  44.         app.Workbooks.Close();     
  45.         app.Quit();     
  46.     }  
worksheet.get_Range(worksheet.Cells[1, 1], worksheet.Cells[10, 10]).Locked = false;
   //保护工作表
  worksheet.Protect("MyPassword", Type.Missing, Type.Missing, Type.Missing,
           Type.Missing, Type.Missing, Type.Missing, Type.Missing,
           Type.Missing, Type.Missing, Type.Missing, Type.Missing,
           Type.Missing, true, true, true);


  ///     
      ///   在工作表中插入行,并调整其他行以留出空间   
      ///     
      ///     
  当前工作表   
      ///     
  欲插入的行索引   
      private   void   InsertRows(Excel.Worksheet   sheet,   int   rowIndex)   
      {   
        range   =   (Excel.Range)sheet.Rows[rowIndex,   missing];         
        //object   Range.Insert(object   shift,   object   copyorigin);     
        //shift:   Variant类型,可选。指定单元格的调整方式。可以为下列   XlInsertShiftDirection   常量之一:   
        //xlShiftToRight   或   xlShiftDown。如果省略该参数,Microsoft   Excel   将根据区域形状确定调整方式。   
        range.Insert(Excel.XlInsertShiftDirection.xlShiftDown,   missing);       
      }   
    
      ///     
      ///   在工作表中删除行   
      ///     
      ///     
  当前工作表   
      ///     
  欲删除的行索引   
      private   void   DeleteRows(Excel.Worksheet   sheet,   int   rowIndex)   
      {   
        range   =   (Range)sheet.Rows[rowIndex,   missing];   
        range.Delete(Excel.XlDeleteShiftDirection.xlShiftUp);   
      }   
    
      ///     
      ///   退出Excel,并且释放调用的COM资源   
      ///     
      private   void   Dispose()   
      {   
        book.Close(missing,   missing,   missing);   
        app.Workbooks.Close();   
        app.Quit();   
	}




----------------------------NOPI导出Excel-------------------------------

改单元格样式点击打开链接

[csharp] view plaincopyprint?
  1. dll下载地址:<A href="http://download.csdn.net/detail/happy09li/4436160" target=_blank>点击打开链接</A>  
  2. using NPOI;  
  3. using NPOI.HPSF;  
  4. using NPOI.HSSF;  
  5. using NPOI.HSSF.UserModel;  
  6. public static void exportExcel(DataTable dtSource, string strFileName)  
  7.         {  
  8.             HSSFWorkbook workbook = new HSSFWorkbook();  
  9.             HSSFSheet sheet = workbook.CreateSheet();  
  10.             //填充表头      
  11.             HSSFRow dataRow = sheet.CreateRow(0);  
  12.             HSSFCellStyle headStyle = workbook.CreateCellStyle();  
  13.             headStyle.Alignment = CellHorizontalAlignment.CENTER;  
  14.             HSSFFont font = workbook.CreateFont();  
  15.             font.FontHeightInPoints = 20;  
  16.             font.Boldweight = 700;  
  17.             headStyle.SetFont(font);  
  18.               
  19.             foreach (DataColumn column in dtSource.Columns)  
  20.             {  
  21.                 dataRow.CreateCell(column.Ordinal).SetCellValue(column.ColumnName);  
  22.                 dataRow.GetCell(column.Ordinal).CellStyle = headStyle;  
  23.               //  dataRow.GetCell(column.Ordinal).c   
  24.                 //设置列宽      
  25.                //sheet.SetColumnWidth(column.Ordinal,column.Caption.Length*20);    
  26.             }  
  27.             //填充内容      
  28.             for (int i = 0; i < dtSource.Rows.Count; i++)  
  29.             {  
  30.                 dataRow = sheet.CreateRow(i + 1);  
  31.                 for (int j = 0; j < dtSource.Columns.Count; j++)  
  32.                 {  
  33.                     dataRow.CreateCell(j).SetCellValue(dtSource.Rows[i][j].ToString());  
  34.                 }  
  35.             }</pre><pre name="code" class="csharp"> for (int m = 0; m < dtData.Columns.Count - 1; m++)  
  36.         {  
  37.           for (int n = 0; n < dtData.Rows.Count - 1; n++)  
  38.           {  
  39.             if (sheet.GetRow(n).GetCell(m).ToString() == sheet.GetRow(n + 1).GetCell(m).ToString() && !string.IsNullOrEmpty(sheet.GetRow(n).GetCell(m).ToString()))  
  40.             {  
  41.               sheet.AddMergedRegion(new NPOI.HSSF.Util.Region(n, m, n + 1, m));  
  42.             }  
  43.             //else if (sheet.GetRow(n).GetCell(m).ToString() == sheet.GetRow(n).GetCell(m + 1).ToString())   
  44.             //{   
  45.             //  sheet.AddMergedRegion(new Region(n, m, n, m + 1));   
  46.             //}   
  47.           }  
  48.         }  
  49.             //保存      
  50.             using (MemoryStream ms = new MemoryStream())  
  51.             {  
  52.                 using (FileStream fs = new FileStream(strFileName, FileMode.Create, FileAccess.Write))  
  53.                 {  
  54.                     workbook.Write(fs);  
  55.                 }  
  56.             }  
  57.             workbook.Dispose();     
  58.         }  
dll下载地址:点击打开链接
using NPOI;
using NPOI.HPSF;
using NPOI.HSSF;
using NPOI.HSSF.UserModel;
public static void exportExcel(DataTable dtSource, string strFileName)
        {
            HSSFWorkbook workbook = new HSSFWorkbook();
            HSSFSheet sheet = workbook.CreateSheet();
            //填充表头   
            HSSFRow dataRow = sheet.CreateRow(0);
            HSSFCellStyle headStyle = workbook.CreateCellStyle();
            headStyle.Alignment = CellHorizontalAlignment.CENTER;
            HSSFFont font = workbook.CreateFont();
            font.FontHeightInPoints = 20;
            font.Boldweight = 700;
            headStyle.SetFont(font);
            
            foreach (DataColumn column in dtSource.Columns)
            {
                dataRow.CreateCell(column.Ordinal).SetCellValue(column.ColumnName);
                dataRow.GetCell(column.Ordinal).CellStyle = headStyle;
              //  dataRow.GetCell(column.Ordinal).c
                //设置列宽   
               //sheet.SetColumnWidth(column.Ordinal,column.Caption.Length*20); 
            }
            //填充内容   
            for (int i = 0; i < dtSource.Rows.Count; i++)
            {
                dataRow = sheet.CreateRow(i + 1);
                for (int j = 0; j < dtSource.Columns.Count; j++)
                {
                    dataRow.CreateCell(j).SetCellValue(dtSource.Rows[i][j].ToString());
                }
            }</pre><pre name="code" class="csharp"> for (int m = 0; m < dtData.Columns.Count - 1; m++)
        {
          for (int n = 0; n < dtData.Rows.Count - 1; n++)
          {
            if (sheet.GetRow(n).GetCell(m).ToString() == sheet.GetRow(n + 1).GetCell(m).ToString() && !string.IsNullOrEmpty(sheet.GetRow(n).GetCell(m).ToString()))
            {
              sheet.AddMergedRegion(new NPOI.HSSF.Util.Region(n, m, n + 1, m));
            }
            //else if (sheet.GetRow(n).GetCell(m).ToString() == sheet.GetRow(n).GetCell(m + 1).ToString())
            //{
            //  sheet.AddMergedRegion(new Region(n, m, n, m + 1));
            //}
          }
        }
            //保存   
            using (MemoryStream ms = new MemoryStream())
            {
                using (FileStream fs = new FileStream(strFileName, FileMode.Create, FileAccess.Write))
                {
                    workbook.Write(fs);
                }
            }
            workbook.Dispose();   
        }



 

posted on 2012-12-06 16:53  五蕴  阅读(521)  评论(0)    收藏  举报

刷新页面返回顶部
 
博客园  ©  2004-2026
浙公网安备 33010602011771号 浙ICP备2021040463号-3