日期:2014-05-18  浏览次数:20938 次

C#操作Excel表格
请问怎么用C#操作Excel表格,主要是要写的数据相当大,所以有以下几个要求:
  1.写的时候不需要打开excel表格,
  2.需要具体名字的不同sheet,
  3.需要具体操作各个sheet下面的每一个cell
  4.最好可以直接用循环之类的语句操作cells

先谢谢各位了。

------解决方案--------------------
Microsoft.Office.Interop.Excel.Application xlApp = new Microsoft.Office.Interop.Excel.Application();
Workbooks workbooks = xlApp.Workbooks;
Workbook workbook = workbooks.Add(XlWBATemplate.xlWBATWorksheet);
Worksheet worksheet = (Worksheet)workbook.Worksheets[1];
object[,] datas = new object[table.Rows.Count + 2, table.Columns.Count + 1];
 for (int i = 0; i < table.Columns.Count; i++) //写入字段
{
datas[0, i] = table.Columns[i].ColumnName;
}
Range range = worksheet.get_Range(worksheet.Cells[1, 1], worksheet.Cells[1, table.Columns.Count]);
range.Interior.ColorIndex = 15;//15代表灰色
range.Font.Bold = true;
range.Font.Size = 9;
int r = 0;
for (r = 0; r < table.Rows.Count; r++)
 {
for (int i = 0; i < table.Columns.Count; i++)
 {
object obj = table.Rows[r][table.Columns[i].ColumnName];
datas[r + 1, i] = obj;//在obj.ToString()前加单引号是为了防止自动转化格式
 }
 }
 Range fchR = worksheet.get_Range(worksheet.Cells[1, 1], worksheet.Cells[table.Rows.Count + 2, table.Columns.Count + 1]);
fchR.Value2 = datas;
 worksheet.Columns.EntireColumn.AutoFit();//列宽自适应。
range = worksheet.get_Range(worksheet.Cells[1, 1], worksheet.Cells[table.Rows.Count + 1, table.Columns.Count]);
//15代表灰色
range.Font.Size = 9;
range.RowHeight = 14.25;
range.Borders.LineStyle = 1;
range.HorizontalAlignment = 1;
workbook.Saved = true;
workbook.SaveCopyAs(saveFileName);
xlApp.Quit();
GC.Collect();//强行销毁
------解决方案--------------------
using Excel;
public string ExportAsExcel(DataGridView dvw, string filePath)
{
Excel.Application excel = new Excel.Application();
Workbook book = excel.Workbooks.Add(Missing.Value);
Sheets sheet = book.ActiveSheet as Sheets;
excel.Visible = false;
for (int j = 0; j < dvw.Columns.Count; j++)
excel.Cells[1, j + 1] = dvw.Columns[j].HeaderText;
for (int i = 0; i < dvw.Rows.Count; i++)
{
for (int j = 0; j < dvw.Columns.Count; j++)
excel.Cells[i + 2, j + 1] = dvw.Rows[i].Cells[j].Value;
}
book.SaveAs(filePath, Missing.Value, Missing.Value, Missing.Value, Missing.Value, Missing.Value, XlSaveAsAccessMode.xlExclusive, Missing.Value, Missing.Value, Missing.Value, Missing.Value, Missing.Value);
book.Close(false, Missing.Value, Missing.Value);
excel.Workbooks.Close();
excel.Quit();
return filePath;
}

这是我看了网上好好多多的EXCEL后改的,精简,就是有点慢,