public class OperateExecl
{
//读取execl到datatable
public static DataTable ReadFile(string path)
{ string strConn="";
if (Path.GetExtension(path).ToLower().Equals(".xlsx")) //Excel2007
{
strConn = @"Provider=Microsoft.ACE.OLEDB.12.0;Data Source=" + path + ";Extended Properties='Excel 12.0;HDR=YES';";
}
else //excel2003
{
strConn = "Provider = Microsoft.Jet.OLEDB.4.0;Data Source=" + path + ";Extended Properties=Excel 8.0;";
}
OleDbConnection conn = new OleDbConnection(strConn);
conn.Open();
string strExcel = "";
OleDbDataAdapter myCommand = null;
DataSet ds = null;
DataTable schemaTable = conn.GetOleDbSchemaTable(System.Data.OleDb.OleDbSchemaGuid.Tables, null);
string tableName = schemaTable.Rows[0][2].ToString().Trim();
strExcel = "select * from [" + tableName + "]";
myCommand = new OleDbDataAdapter(strExcel, strConn);
ds = new DataSet();
myCommand.Fill(ds, "table1");
return ds.Tables[0];
}
//设置单元格颜色
public static void SetColor()
{
Microsoft.Office.Interop.Excel.ApplicationClass execlapp = new Microsoft.Office.Interop.Excel.ApplicationClass(); Microsoft.Office.Interop.Excel.Workbook wb = execlapp.Workbooks.Open(@"C:UserszhangshixiaoDesktop数据导入模板(1).xlsx"); Microsoft.Office.Interop.Excel.Worksheet ws = (Microsoft.Office.Interop.Excel.Worksheet)wb.Sheets.get_Item(1); Microsoft.Office.Interop.Excel.Range range = (Microsoft.Office.Interop.Excel.Range)ws.Cells[1, 1];
range.Interior.Color = Color.FromArgb(255, 0, 0);
wb.Save();
wb.Close();
}
}