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

C#对Excel的一些操作【一】

2012-08-16 22:30 337 查看
C#操作Excel的方式多种多样,以下为个人实践中的一些总结,留个笔记方便以后查看,陆续更新中。。。

进入正题:

一:将Excel的数据直接导入到SQL数据库中

这个需要Excel文件与数据库中的表的字段一致,或者指定每一个字段也行;

首先读取Excel里面的内容:

string strCon = " Provider = Microsoft.Jet.OLEDB.4.0 ; " + "Data Source =" + this.txtPath.Text + ";Extended Properties=Excel 8.0";
OleDbConnection myConn = new OleDbConnection(strCon);
string sql = "SELECT * FROM [Sheet1$]";
try
{
myConn.Open();
OleDbDataAdapter oda = new OleDbDataAdapter(sql, myConn);
oda.Fill(ds, "[Sheet1$]");
myConn.Close();
this.dataGridView1.DataSource = ds.Tables[0];
}
catch (Exception ex)
{

MessageBox.Show(ex.Message);
}


然后循环将每一条数据Insert到数据库中:

string connectionString = @"server=SQL2008; database=ExcelDB; uid=sa;pwd=123123";
SqlConnection con = new SqlConnection(connectionString);
DataGrid mygrid = new DataGrid();
mygrid.SetDataBinding(ds, "[Sheet1$]");
int num = ds.Tables[0].Rows.Count;
for (int i = 0; i < num; i++)
{
string value1 = mygrid[i, 0].ToString();
string value2 = mygrid[i, 1].ToString();
string value3 = mygrid[i, 2].ToString();
string value4 = mygrid[i, 3].ToString();
string value5 = mygrid[i, 4].ToString();
string strsql = "INSERT INTO tb_01 VALUES('" + value1 + "','" + value2 + "','" + value3 + "','" + value4 + "','" + value5 + "')";
con.Open();
SqlCommand cmd = new SqlCommand(strsql, con);
cmd.ExecuteNonQuery();
con.Close();
}


 

二:将SQL数据库中的数据写入到Excel

通常有很多报表会要求将后台的数据写入到一个固定的模板文件中,那么可以这样操作:

using Excel = Microsoft.Office.Interop.Excel;
Excel.Application xApp = new Excel.ApplicationClass();
Excel.Workbook xBook = xApp.Workbooks._Open(txtPath.Text.Trim(),
Missing.Value, Missing.Value, Missing.Value, Missing.Value
, Missing.Value, Missing.Value, Missing.Value, Missing.Value
, Missing.Value, Missing.Value, Missing.Value, Missing.Value);

Excel.Worksheet xSheet = (Excel.Worksheet)xBook.Sheets[1];

Excel.Range rng1 = xSheet.get_Range("A1", Missing.Value);
rng1.Value2 = this.txt01.Text.Trim();

Excel.Range rng2 = xSheet.get_Range("B1", Missing.Value);
rng2.Value2 = this.txt02.Text.Trim();

Excel.Range rng3 = xSheet.get_Range("C1", Missing.Value);
rng3.Value2 = this.txt03.Text.Trim();

Excel.Range rng4 = xSheet.get_Range("D1", Missing.Value);
rng4.Value2 = this.txt04.Text.Trim();

xBook.Save();

xApp.Quit();


A1,B1,C1,D1就是Excel里面的单元格坐标,这个根据要求可以任意更改,

Excel操作完成之后务必要将其退出来,不然服务器上面Excel的进程会

越来越多。

三.将WinForm里面DataGridView的数据导出到Excel里面。

该实例将所有的数据放到一个数组里面,然后再从数组里面导入到Excel,在速度上确实挺快的,

直接从DataGridView里面导入的话10000条数据大约要1分钟左右,但是从数组里面导出去的话

只有2秒钟不到的样子。

if (this.dataGridView1.Rows.Count > 0)
{
DateTime dt = DateTime.Now;               //导出Excel表时间
string title = "XXX报表  导出时间:" + dt.ToString(); //excel表头
Microsoft.Office.Interop.Excel.Application ep = new Microsoft.Office.Interop.Excel.ApplicationClass();
ep.Application.Workbooks.Add(true);

ep.get_Range("A1", "Z1").MergeCells = true;   //合并第一行

ep.Cells[1, 1] = title;                       //Excel添加表头到第一个单元格
ep.get_Range("A1", "Z1").MergeCells = true;   //合并第一行
ep.get_Range("A1", "Z1").HorizontalAlignment = Microsoft.Office.Interop.Excel.XlHAlign.xlHAlignLeft; //表头居左
ep.get_Range("A1", "Z1").Font.Name = "宋体";    //设置字体
ep.get_Range("A1", "Z1").Font.Bold = true;

ep.get_Range("A1", "Z1").Font.Size = 15;        //文字大小
ep.get_Range("A1", "Z1").RowHeight = 35;        //设置标题行高

//列标题设置(字段,Excel表的第二行,从dataGridView1字段中获取)
for (int i = 1; i <= 5; i++)
{
ep.Cells[2, i] = dataGridView1.Columns[i - 1].HeaderText.ToString();
}

ep.get_Range("A2", "Z2").Font.Name = "宋体";    //设置字体
ep.get_Range("A2", "Z2").Font.Bold = true;      //字体加粗
ep.get_Range("A2", "Z2").Font.Size = 10;        //文字大小
ep.get_Range("A2", "Z2").RowHeight = 20;        //设置标题行高

int rowCount = 0;
for (int i = 0; i < dataGridView1.Rows.Count; i++)    //统计dataGridView1有效行
{
if (dataGridView1.Rows[i].Cells[0].Value.ToString() == "")
{
break;
}
else
{
rowCount++;
}

}

string[,] dataArray = new string[rowCount, 5];
for (int i = 0; i < rowCount; i++)
{
for (int j = 0; j < 5; j++)
{
dataArray[i, j] = dataGridView1.Rows[i].Cells[j].Value.ToString();
}
}

ep.get_Range("A3", ep.Cells[rowCount + 2, 5]).Value2 = dataArray;     //填充数据
ep.get_Range("A2", ep.Cells[rowCount + 2, 2]).WrapText = true;      //设置文字自动换行
ep.get_Range("A2", ep.Cells[rowCount + 2, 5]).Font.Size = 10;       //字体大小设置
string strRange = "2:" + Convert.ToString(rowCount + 2);
((Microsoft.Office.Interop.Excel.Range)ep.Rows[strRange, System.Type.Missing]).RowHeight = 40;   //所有行高为40
ep.get_Range("A2", ep.Cells[rowCount + 2, 2 + 5]).EntireColumn.AutoFit();
ep.get_Range("A2", ep.Cells[rowCount + 2, 5]).Borders.LineStyle = 1;

SaveFileDialog saveFileDialog1 = new SaveFileDialog();
saveFileDialog1.FileName = DateTime.Now.ToLocalTime().ToString("yyyyMMddHHmmss");
saveFileDialog1.DefaultExt = "xls";

saveFileDialog1.Filter = " Excel files(*.xls)|*.xls|All files(*.*)|*.*";
saveFileDialog1.Title = "保存数据";
saveFileDialog1.FilterIndex = 2;
saveFileDialog1.RestoreDirectory = true;

if (saveFileDialog1.ShowDialog() == DialogResult.OK)
{
ep.Workbooks[1].SaveAs(saveFileDialog1.FileName, Missing.Value, Missing.Value, Missing.Value, Missing.Value, Missing.Value, Microsoft.Office.Interop.Excel.XlSaveAsAccessMode.xlNoChange, Missing.Value, Missing.Value, Missing.Value, Missing.Value, Missing.Value);
}
ep.Workbooks.Close();
ep.Quit();

MessageBox.Show(DateTime.Now.ToLocalTime().ToString("yyyyMMddHHmmss") + "的资料保存成功", "提示", MessageBoxButtons.OK);
}
else
{
MessageBox.Show("没有可导出数据");
}


 

四.将后台数据转换为图表格式

using Excel = Microsoft.Office.Interop.Excel;
Excel.Application ThisApplication = null;
Excel.Workbooks m_objBooks = null;
Excel._Workbook ThisWorkbook = null;
Excel.Worksheet xlSheet = null;

string strCon = @"server=sql2008;database=exceldb;uid=sa;pwd=123123";
private void FrmChart_Load(object sender, EventArgs e)
{
SqlConnection con = new SqlConnection(strCon);
DataSet ds = new DataSet();
con.Open();
SqlDataAdapter da = new SqlDataAdapter("select * from tb_02", con);
da.Fill(ds, "tb_02");
this.dataGridView1.DataSource = ds.Tables[0];
con.Close();

}

private void CreateDatasheet()
{
xlSheet = (Excel.Worksheet)ThisWorkbook.
Worksheets.Add(Type.Missing, ThisWorkbook.ActiveSheet,
Type.Missing, Type.Missing);

xlSheet.Name = "DataList";
}

private void CreateData()
{
for (int i = 1; i <= 12; i++)
{
xlSheet.Cells[i, 1] = dataGridView1.Rows[i - 1].Cells[1].Value.ToString();
xlSheet.Cells[i, 2] = dataGridView1.Rows[i-1].Cells[4].Value.ToString();
}
}

private void btnCreateChart_Click(object sender, EventArgs e)
{
try
{
ThisApplication = new Excel.Application();
m_objBooks = (Excel.Workbooks)ThisApplication.Workbooks;
ThisWorkbook = (Excel._Workbook)(m_objBooks.Add(Type.Missing));
ThisApplication.DisplayAlerts = false;
this.CreateDatasheet();
this.CreateData();
CreateChart();

ThisWorkbook.SaveAs(@"C:\TEST.xls", Type.Missing, Type.Missing,
Type.Missing, Type.Missing, Type.Missing, Excel.XlSaveAsAccessMode.xlNoChange,
Type.Missing, Type.Missing, Type.Missing, Type.Missing, Type.Missing);

}
catch (Exception ex)
{
MessageBox.Show(ex.Message);
}
finally
{
ThisWorkbook.Close(Type.Missing, Type.Missing, Type.Missing);
ThisApplication.Workbooks.Close();

ThisApplication.Quit();
System.Runtime.InteropServices.Marshal.ReleaseComObject(ThisWorkbook);
System.Runtime.InteropServices.Marshal.ReleaseComObject(ThisApplication);
ThisWorkbook = null;
ThisApplication = null;
GC.Collect();
this.Close();
}

}

private void CreateChart()
{
Excel.Chart xlChart = (Excel.Chart)ThisWorkbook.Charts.
Add(Type.Missing, xlSheet, Type.Missing, Type.Missing);

Excel.Range cellRange = (Excel.Range)xlSheet.Cells[1, 1];
xlChart.ChartWizard(cellRange.CurrentRegion,
Excel.XlChartType.xl3DColumn, Type.Missing,
Excel.XlRowCol.xlColumns, 1, 0, true,
"Prod OutPut", "Month", "OutPut","");

xlChart.Name = "Chart";

Excel.ChartGroup grp = (Excel.ChartGroup)xlChart.ChartGroups(1);
grp.GapWidth = 20;
grp.VaryByCategories = true;

Excel.Series s = (Excel.Series)grp.SeriesCollection(1);
s.BarShape = XlBarShape.xlCylinder;
s.HasDataLabels = true;

xlChart.Legend.Position = XlLegendPosition.xlLegendPositionTop;
xlChart.ChartTitle.Font.Size = 24;
xlChart.ChartTitle.Shadow = true;
xlChart.ChartTitle.Border.LineStyle = Excel.XlLineStyle.xlContinuous;

Excel.Axis valueAxis = (Excel.Axis)xlChart.Axes(Excel.XlAxisType.xlValue, XlAxisGroup.xlPrimary);
valueAxis.AxisTitle.Orientation = -90;

Excel.Axis categoryAxis = (Excel.Axis)xlChart.Axes(Excel.XlAxisType.xlCategory, XlAxisGroup.xlPrimary);

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