1.System.Data.DataTable连接数据库
ExcelFile 是excel的完整路径
//OleDbConnection conExcel = new OleDbConnection(@"Provider=Microsoft.Jet.OLEDB.4.0;Data Source=" + ExcelFile + ";Extended Properties=Excel 8.0");
//if (conExcel.State == ConnectionState.Closed)
//{
// conExcel.Open();
//}
2.获取第一个sheet表名称
不建议写死,程序自动获取下也很快的
System.Data.DataTable dtTmp = conExcel.GetOleDbSchemaTable(OleDbSchemaGuid.Tables, new object[] { null, null, null, "TABLE" });
string tableName = dtTmp.Rows[0][2].ToString().Trim();
3.获取datatable
"select * from [" + tableName + "]"
执行这个sql语句吧,剩下的就是datatable的操作了
根据DataTable可以获取各行各列的值,但似乎不稳定,有时只能获取空值而实际明明有值
4.com方式打开excel
需引用Microsoft.Office.Interop.Excel
object missing = System.Type.Missing;
Application app = new ApplicationClass();
////打开excel,注意空参数不可以用null
Workbook wBook = app.Workbooks.Open(ExcelFile, missing, missing, missing, missing, missing, missing, missing, missing, missing, missing, missing, missing, missing, missing);
app.Visible = false;
//设置禁止弹出保存和覆盖的询问提示框
app.DisplayAlerts = false;
app.AlertBeforeOverwriting = false;
////打开第一个Worksheet
Worksheet wSheet = wBook.Worksheets[1] as Worksheet;
////写值
wSheet.Cells[行, 列] = "你想写的值";
////获取cell的值,注意不可用wSheet.Cells[行, 列]获取,这样一般得到"System.__ComObject"
Range ra = wSheet.get_Range(wSheet.Cells[i, j], wSheet.Cells[i, j]); ////此处是单元格范围,自己决定多大
string sVal = ra.Text.ToString();
////判断单元格是否有公式
ra.Formula.ToString().IndexOf("=") >= 0
////设置excel单元格样式,很多的,自己百度下吧
////这个是设置单元格的边框宽度
Range range = wSheet.get_Range(wSheetDes.Cells[i, j], wSheetDes.Cells[i, j]);
range.Borders[XlBordersIndex.xlEdgeBottom].Weight = 2;
range.Borders[XlBordersIndex.xlEdgeLeft].Weight = 2;
range.Borders[XlBordersIndex.xlEdgeRight].Weight = 2;
range.Borders[XlBordersIndex.xlEdgeTop].Weight = 2;
Range range = wSheetDes.get_Range(wSheet.Cells[i, j], wSheet.Cells[i, j]);
range.Borders.LineStyle = Microsoft.Office.Interop.Excel.XlLineStyle.xlContinuous;
range.BorderAround(XlLineStyle.xlContinuous, XlBorderWeight.xlThin, XlColorIndex.xlColorIndexAutomatic, System.Drawing.Color.Black.ToArgb());
//保存工作簿,方法很多,自己决定怎么用
wSheet.SaveAs(ExcelFile, missing, missing, missing, missing, missing, missing, missing, missing, missing);
wBook.Save();
app.Save(ExcelFile);
app.SaveWorkspace(ExcelFile);
////退出,比较麻烦
wBook.Close(true, missing, missing);
wSheet = null;
wBook = null;
app.Quit();
app = null;
System.GC.Collect();
System.GC.WaitForFullGCComplete();
全部关掉然后置为null,再强制垃圾回收即可
常用的大概这么多,应该够用了