• c# datagridview导出excel(写文本) 纵一苇之所如


    转自(http://www.cnblogs.com/saturn/archive/2012/08/26/2657308.html)和网上其他

    资料

    SaveFileDialog saveFileDialog = new SaveFileDialog();
                saveFileDialog.Filter = "Execl files (*.xls)|*.xls";
                saveFileDialog.FilterIndex = 0;
                saveFileDialog.RestoreDirectory = true;
                saveFileDialog.CreatePrompt = true;
                saveFileDialog.Title = "Export Excel File";
                saveFileDialog.ShowDialog();
                if (saveFileDialog.FileName == "")
                    return;

                Stream myStream;


               
                myStream = saveFileDialog.OpenFile();

                StreamWriter sw = new StreamWriter(myStream, System.Text.Encoding.GetEncoding(-0));
                string str = "";

                try
                {
                    //写dataGridView1表标题
                    for (int i = 0; i < dataGridView1.ColumnCount; i++)
                    {
                        if (i > 0)
                        {
                            str += "\t";
                        }
                        str += dataGridView1.Columns[i].HeaderText.Trim();
                    }
                    sw.WriteLine(str);


                    //写dataGridView1表內容
                    for (int j = 0; j < dataGridView1.Rows.Count; j++)
                    {
                        string tempStr = "";
                        for (int k = 0; k < dataGridView1.Columns.Count; k++)
                        {
                            if (k > 0)
                            {
                                tempStr += "\t";
                            }
                            tempStr += dataGridView1.Rows[j].Cells[k].Value.ToString().Trim() ;
                            tempStr += dataGridView1.Rows[j].Cells[k].Value;


                        }
                         sw.WriteLine(tempStr);

                    }
                    sw.Close();
                    myStream.Close();


                }

                catch (Exception ex)
                {
                    MessageBox.Show(ex.ToString());
                }
                finally
                {
                    sw.Close();
                    myStream.Close();
                }

    第二种:

     //写dataGridView1表标题
                string str = "";
                for (int i = 0; i < dataGridView1.ColumnCount; i++)
                     {
                         if (i > 0)
                         {
                             str += "\t";
                         }
                         str += dataGridView1.Columns[i].HeaderText.Trim();
                         if (i == dataGridView1.Columns.Count - 1)
                         {
                             str += "\n";
                         }
                     }


                for (int i = 0; i < dataGridView1.Rows.Count; i++) //循环写入dataGridView中的内容
                {

                    for (int j = 0; j < dataGridView1.Columns.Count; j++)
                    {
                        if (j > 0)
                        {
                            str += "\t";
                        }
                       
                        //if (j == 0 &&i==0)
                        //{
                        //    str += "\n";
                        //}
                        str += dataGridView1.Rows[i].Cells[j].Value;
                        if (j == dataGridView1.Columns.Count - 1 )
                        {
                            str += "\n";
                        }
                    }
                }
               
              
                DateTime now = DateTime.Now;
                string newname = now.ToString("yyyymmddhhmmss");//确保以下写入的文件名唯一
                File.WriteAllText("MarkLog/MagazineMarked" + newname + ".xls", str, Encoding.Default);

    第三种:

     /// <summary>
    /// DataGridView导出Excel
    /// </summary>
    /// <param name="strCaption">Excel文件中的标题</param>
    /// <param name="myDGV">DataGridView 控件</param>
     ///  <param name="markNo">用来辨别勾的是报纸还是杂志</param>
         private static void ExportExcel(string strCaption, DataGridView myDGV, string markNo)
          {
              
                // 列索引,行索引,总列数,总行数
                int ColIndex = 0;
                int RowIndex = 0;
                int ColCount = myDGV.ColumnCount;
                int RowCount = myDGV.RowCount;

                if (myDGV.RowCount == 0)
                {
                    MessageBox.Show("ataGridView中无记录");
                   
                }

                // 创建Excel对象
                Microsoft.Office.Interop.Excel.Application xlApp = new Microsoft.Office.Interop.Excel.ApplicationClass();
                if (xlApp == null)
                {
                    MessageBox.Show("Excel无法启动");
                      
                }
                try{
                        // 创建Excel工作薄
                        Microsoft.Office.Interop.Excel.Workbook xlBook = xlApp.Workbooks.Add(true);
                        Microsoft.Office.Interop.Excel.Worksheet xlSheet = (Microsoft.Office.Interop.Excel.Worksheet)xlBook.Worksheets[1];
                        // 设置标题
                        Microsoft.Office.Interop.Excel.Range range = xlSheet.get_Range(xlApp.Cells[1, 1], xlApp.Cells[1, ColCount]); //标题所占的单元格数与DataGridView中的列数相同
                        range.MergeCells = true;
                        xlApp.ActiveCell.FormulaR1C1 = strCaption;
                        xlApp.ActiveCell.Font.Size = 20;
                        xlApp.ActiveCell.Font.Bold = true;
                        xlApp.ActiveCell.HorizontalAlignment = Microsoft.Office.Interop.Excel.Constants.xlCenter;
                        // 创建缓存数据
                        object[,] objData = new object[RowCount + 1, ColCount];
                        //获取列标题
                        foreach (DataGridViewColumn col in myDGV.Columns)
                        {
                              objData[RowIndex, ColIndex++] = col.HeaderText;
                        }
                        // 获取数据
                        for (RowIndex = 1; RowIndex < RowCount; RowIndex++)
                        {
                                 for (ColIndex = 0; ColIndex < ColCount; ColIndex++)
                                {                        
                                        if (myDGV[ColIndex, RowIndex - 1].ValueType == typeof(string)|| myDGV[ColIndex, RowIndex - 1].ValueType == typeof(DateTime))//这里就是验证DataGridView单元格中的类型,如果是string或是DataTime类型,则在放入缓 存时在该内容前加入" ";
                                        {
                                                objData[RowIndex, ColIndex] = "" + myDGV[ColIndex, RowIndex - 1].Value;
                                        }
                                        else
                                        {
                                                objData[RowIndex, ColIndex] = myDGV[ColIndex, RowIndex - 1].Value;
                                        }
                                }
                               System.Windows.Forms.Application.DoEvents();
                        }
                        // 写入Excel
                        range = xlSheet.get_Range(xlApp.Cells[2, 1], xlApp.Cells[RowCount, ColCount]);
                        range.Value2 = objData;

                        //保存
                        xlBook.Saved = true;
                        if (markNo == "1")
                        {
                            xlBook.SaveCopyAs(System.Windows.Forms.Application.StartupPath + "/MarkLog/ReceivedAndMarked" + DateTime.Now.ToString("yyyyMMddHHmmss") + ".xls");
                            //返回值
                        }
                        else {
                            xlBook.SaveCopyAs(System.Windows.Forms.Application.StartupPath + "/MarkLog/Marked" + DateTime.Now.ToString("yyyyMMddHHmmss") + ".xls");
                            //返回值
                        }

                    }
              catch (Exception err)
                    {
                        MessageBox.Show(err.ToString());
                    }
                    finally
                    {
                        xlApp.Quit();
                        GC.Collect(); //强制回收
                    }
            }

  • 相关阅读:
    前端学习笔记系列一:5 在项目中引入阿里图标icon
    前端学习笔记系列一:3 Vue中的nextTick
    前端学习笔记系列一:4 vue中@click.native
    学习习惯
    美团作价27亿美元正式收购摩拜
    北京 一卡通 退卡
    愚人自以慧,智者自以愚。
    袁隆平分享8字成功经验
    性能计数器 叹号
    升级 windows 2016
  • 原文地址:https://www.cnblogs.com/panjinzhao/p/2849283.html
Copyright © 2020-2023  润新知