注册 登录
编程论坛 C# 论坛

C# 写Excel表 单元格操作

koowa 发布于 2015-05-27 13:50, 1057 次点击
我的程序大致意思为
string cell[5] = {"B","C","D","E","F"};

For( i=1;i<=40;i++)
     For(j=1;j<=5;j++)
         {cellname= cell[j]+string.format("%d",i+1);
          string data = "22.5";
         Excel.Write("sheet1",cellname,(i+1),data);}

Excel操作函数为:
write(string sheetname, string cellname, int lines, string writedata)
{
    OleDbCommand command= null;
    if(this,conOleDB != null)
      {
              try
        {
            this.conOleDB.Open();
   command = new OleDbCommand(string.Format("UPDATE [{0}${1}:{2}] Set F{3}=\"{4}\"", new object[] { sheetName, cellName, cellName, Lines, value2Write }), this.conOleDB);
            command.ExecuteNonQuery();
        }
      catch(Exception exception)
      {
            .......
       }
}

如果想实现在Excel表指定区域(2-42行,(B-F)列写入数据,应该如何更改)??

这段代码可以实现写操作,但每次只写入第一行(B-F)单元格,坐等高手指点~
3 回复
#2
Maick2015-05-27 14:29
"UPDATE [{0}${1}:{2}] Set F{3}=\"{4}\"", new object[] { sheetName, cellName, cellName, Lines, value2Write }
这句什么意思?
#3
koowa2015-05-27 14:36
回复 2楼 Maick
"UPDATE [{0}${1}:{2}] Set F{3}=\"{4}\"", new object[] { sheetName, cellName, cellName, Lines, value2Write }
sheetName, cellName, cellName, Lines, value2Write是赋给前面字符串的变量参数
如sheet1,C5,C5,5,22.5
那么前面UPDATE语句就变为
UPDATE [sheet1$C5:C5] Set F5="22.5";

因为我操作的对象是一个空表。想从第二行B列开始写数据,感觉F不是操作列的,说它操作行,F5也没有在第5行开始写,你能看出这段代码怎么改吗?或者哪里错了?
#4
gesongs2015-05-28 08:23
看不懂
我把我写的 案例 供你 参考
using Microsoft.Office.Interop.Excel;//引用类

Excel.ApplicationClass xlApp = new Excel.ApplicationClass();
                    if (xlApp == null)
                    {
                        MessageBox.Show("无法创建Excel对象,可能您的机子未安装Excel");
                        return;
                    }


                    Excel.Application excel = new Excel.ApplicationClass();
                    Excel.Workbook Book = excel.Workbooks.Add(Excel.XlWBATemplate.xlWBATWorksheet);
                    Excel.Worksheet sheet;
                    Excel.Range range;
                    //第一个sheet
                    sheet = (Excel.Worksheet)Book.Sheets.Add(Book.Sheets[1], Type.Missing, Type.Missing, Type.Missing);
                    sheet.Name = "111";//sheet名称
        //填充数据
                    for (int i =1; i < 31; i++)//i=30横坐标
                    {
                        for (int j = 1; j < 21; j++)// j=20纵坐标
                        {
                            sheet.Cells[i, j] = (i + "--" + j).ToString();
                            range = sheet.get_Range(sheet.Cells[i, j], sheet.Cells[i, j]);
                        }
                    }
 excel.Cells.WrapText = true;
Book.SaveAs(System.Windows.Forms.Application.StartupPath + "\\Excel\\text.xls", 56, null, null, null, null, Excel.XlSaveAsAccessMode.xlExclusive, null, null, null, null, null);
Book.Close();// 关闭工作薄,即关闭Excel
excel.Quit(); //退出excel对象
1