日期:2014-05-18 浏览次数:20944 次
String TempFileName = Path.GetTempFileName(); SW = new StreamWriter(TempFileName); foreach (DataGridViewRow DR in GvLog.Rows) { // 假设输出1,2,5 列 SW.WriteLine(DR.Cells["第一列"].Value.ToString() + Convert.ToChar((int)Keys.Tab) + DR.Cells["第二列"].Value.ToString() + Convert.ToChar((int)Keys.Tab) + DR.Cells["第五列"].Value.ToString()); ); } SW.Close(); SW = null; StreamReader SR = new StreamReader(TempFileName); Clipboard.Clear(); Clipboard.SetText(SR.ReadToEnd(), TextDataFormat.UnicodeText); Excel.Application ExcelApplication = new Excel.Application(); Excel.Workbooks ExcelWorkbooks = ExcelApplication.Workbooks; Excel.Workbook ExcelWorkbook = ExcelWorkbooks.Add(Missing.Value); Excel.Worksheet ExcelWorksheet = (Excel.Worksheet)ExcelWorkbook.ActiveSheet; ExcelWorksheet.Paste(Missing.Value, Missing.Value); ExcelWorkbook.SaveAs(DlgSaveFile.FileName, Missing.Value, Missing.Value, Missing.Value, Missing.Value, Missing.Value, Excel.XlSaveAsAccessMode.xlShared, Missing.Value, Missing.Value, Missing.Value, Missing.Value, Missing.Value); FreeExcelObject(ExcelWorksheet); ExcelWorkbook.Close(Missing.Value, Missing.Value, Missing.Value); FreeExcelObject(ExcelWorkbook); FreeExcelObject(ExcelWorkbooks); ExcelApplication.Quit(); FreeExcelObject(ExcelApplication);
------解决方案--------------------
根据你要的列,for循环去写,参考 Microsoft.Office.Interop.Excel.Application xlApp = new Microsoft.Office.Interop.Excel.Application(); if (xlApp == null) { MessageBox.Show("无法创建Excel对象,可能您的机器未安装Excel"); return; } Microsoft.Office.Interop.Excel.Workbooks workbooks = xlApp.Workbooks; Microsoft.Office.Interop.Excel.Workbook workbook = workbooks.Add(Microsoft.Office.Interop.Excel.XlWBATemplate.xlWBATWorksheet); Microsoft.Office.Interop.Excel.Worksheet worksheet = (Microsoft.Office.Interop.Excel.Worksheet)workbook.Worksheets[1];//取得sheet1 Microsoft.Office.Interop.Excel.Range range; xlApp.Visible = false; worksheet.Cells[1, 1] = "抽奖结果" + this.cmbCity.SelectedItem.ToString() + "(" + DateTime.Now.ToString("yyyy-MM-dd HH") + ")"; worksheet.get_Range(worksheet.Cells[1, 1], worksheet.Cells[1, 7]).MergeCells = true; //合并单元格 worksheet.get_Range(worksheet.Cells[1