您的位置:首页 > 编程语言 > C#

C#读取execl到datatable,设置execl单元格颜色

2013-09-24 16:06 549 查看
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:\Users\zhangshixiao\Desktop\数据导入模板(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();

}

}
内容来自用户分享和网络整理,不保证内容的准确性,如有侵权内容,可联系管理员处理 点击这里给我发消息
标签: