在以前的項(xiàng)目中,做這些類似的功能也挺多的,,沒保存好,,現(xiàn)在在這里記下,會以后所用:
-
-
-
-
- public static void ExporDataSetToExcel(DataSet ds)
- {
- if (ds == null) return;
-
- string savefilename = "";
- bool filesaved = false;
-
- SaveFileDialog savedialog = new SaveFileDialog();
- savedialog.DefaultExt = "xls";
- savedialog.Filter = "excel文件|*.xls";
- savedialog.FileName = "sheet1";
- savedialog.ShowDialog();
- savefilename = savedialog.FileName;
- if (savefilename.IndexOf(":") < 0) return;
-
- Excel.Application xlapp = new Excel.ApplicationClass();
-
- if (xlapp == null)
- {
- MessageBox.Show("無法創(chuàng)建excel對象,,可能您的機(jī)子未安裝excel");
- return;
- }
-
- Excel.Workbooks workbooks = xlapp.Workbooks;
- Excel._Workbook workbook = workbooks.Add(Excel.XlWBATemplate.xlWBATWorksheet);
- Excel.Worksheet worksheet = (Excel.Worksheet)workbook.Worksheets[1];
- Excel.Range range;
-
-
- long totalcount = ds.Tables[0].Rows.Count;
- long rowread = 0;
- float percent = 0;
-
-
-
- for (int i = 0; i < ds.Tables[0].Columns.Count; i++)
- {
- worksheet.Cells[2, i + 1] = ds.Tables[0].Columns[i].ColumnName;
- range = (Excel.Range)worksheet.Cells[2, i + 1];
- range.Interior.ColorIndex = 15;
- range.Font.Bold = true;
-
- }
-
-
- for (int r = 0; r < ds.Tables[0].Rows.Count; r++)
- {
- for (int i = 0; i < ds.Tables[0].Columns.Count; i++)
- {
- worksheet.Cells[r + 3, i + 1] = ds.Tables[0].Rows[r][i];
- }
- rowread++;
- percent = ((float)(100 * rowread)) / totalcount;
-
- System.Windows.Forms.Application.DoEvents();
- }
-
-
-
- range = worksheet.get_Range(worksheet.Cells[2, 1], worksheet.Cells[ds.Tables[0].Rows.Count + 2, ds.Tables[0].Columns.Count]);
- range.BorderAround(Excel.XlLineStyle.xlContinuous, Excel.XlBorderWeight.xlThin, Excel.XlColorIndex.xlColorIndexAutomatic, null);
-
- range.Borders[Excel.XlBordersIndex.xlInsideHorizontal].ColorIndex = Excel.XlColorIndex.xlColorIndexAutomatic;
- range.Borders[Excel.XlBordersIndex.xlInsideHorizontal].LineStyle = Excel.XlLineStyle.xlContinuous;
- range.Borders[Excel.XlBordersIndex.xlInsideHorizontal].Weight = Excel.XlBorderWeight.xlThin;
-
- if (ds.Tables[0].Columns.Count > 1)
- {
- range.Borders[Excel.XlBordersIndex.xlInsideVertical].ColorIndex = Excel.XlColorIndex.xlColorIndexAutomatic;
- range.Borders[Excel.XlBordersIndex.xlInsideVertical].LineStyle = Excel.XlLineStyle.xlContinuous;
- range.Borders[Excel.XlBordersIndex.xlInsideVertical].Weight = Excel.XlBorderWeight.xlThin;
- }
-
- if (savefilename != "")
- {
- try
- {
- workbook.Saved = true;
- workbook.SaveCopyAs(savefilename);
- filesaved = true;
- MessageBox.Show("文件已經(jīng)成功導(dǎo)出...");
- }
- catch (Exception ex)
- {
- filesaved = false;
- MessageBox.Show("導(dǎo)出文件時(shí)出錯(cuò),文件可能正被打開,!/n" + ex.Message);
- }
- }
- else
- {
- filesaved = false;
- }
- xlapp.Quit();
- GC.Collect();
-
- }
這些代碼可以完成此功能,以后會繼續(xù)完善!