excel生成报表
private void toolStripButton1_Click(object sender, EventArgs e)
{
DataSet ds = new DataSet();
OpenFileDialog openFileDialog=new OpenFileDialog();
openFileDialog.InitialDirectory=@"c:\\";
openFileDialog.Filter = @"*.xlsx|*.xlsx|*.xls|*xls";
openFileDialog.RestoreDirectory=true;
openFileDialog.FilterIndex=1;
if (openFileDialog.ShowDialog()==DialogResult.OK)
{
ds = GetExcelContent(openFileDialog.FileName);
dataGridView1.DataSource = ds.Tables[0].DefaultView;
try
{
dataGridView1.Columns[0].HeaderText = "姓名";
dataGridView1.Columns[1].HeaderText = "Tel";
}
catch { }
}
ReportDocument doc = new ReportDocument();
doc.Load("CrystalReport1.rpt");
TableLogOnInfo tableLogOnInfo = new TableLogOnInfo();
tableLogOnInfo.ConnectionInfo.ServerName = "*.128.99.*";
tableLogOnInfo.ConnectionInfo.DatabaseName = "db";
tableLogOnInfo.ConnectionInfo.UserID = "sa";
tableLogOnInfo.ConnectionInfo.Password = "111111";
doc.Database.Tables[0].ApplyLogOnInfo(tableLogOnInfo);
doc.Database.Tables[0].SetDataSource(ds.Tables[0]);
crystalReportViewer1.ReportSource = doc;
}
private DataSet GetExcelContent(string filepath)
{
//string strCon = "Provider=Microsoft.Jet.OLEDB.4.0;" + "Data Source=" + filepath + ";" + "Extended Properties=Excel 8.0;";
string strCon = string.Format("Provider=Microsoft.ACE.OLEDB.12.0;Data Source={0};Extended Properties=\"Excel 12.0;IMEX=1;{1}\"", filepath,"");
System.Data.OleDb.OleDbConnection myConn = new System.Data.OleDb.OleDbConnection(strCon);
string strCom = "SELECT * FROM [Sheet1$]";
myConn.Open();
System.Data.OleDb.OleDbDataAdapter myCommand = new System.Data.OleDb.OleDbDataAdapter(strCom, myConn);
//创建一个DataSet对象
DataSet myDataSet = new DataSet();
//得到自己的DataSet对象
myCommand.Fill(myDataSet);
//关闭此数据链接
myConn.Close();
return myDataSet;
}