C#datatable导出到Excel

本文介绍了两种数据导出方法,一种使用MicrosoftOfficeExcel的VisualBasicforApplications(VBA),另一种通过NPOI库处理HSSFWorkbook。详细描述了如何设置文件名、选择保存位置、创建工作簿、添加工作表、设置单元格样式并填充数据,最后将数据保存为Excel文件。

摘要生成于 C知道 ,由 DeepSeek-R1 满血版支持, 前往体验 >

第一种方法:

                string fileName = "HHHH";
                string namestr = superTabControl1.SelectedTab.Text.ToString();
 
                //string fileName = DGVthree.SelectedRows[0].Cells["Name"].Value.ToString();//可以在这里设置默认文件名
                string saveFileName = "";//文件保存名
                SaveFileDialog saveDialog = new SaveFileDialog();//实例化文件对象
                saveDialog.FileName = fileName;
                saveFileName = saveDialog.FileName;
                if (DGV2.Rows.Count == 0)
                {
                    MessageBox.Show("当前无数据可导出!");
                    return;
                }
                saveDialog.Title = "请选择要导出的位置";
                saveDialog.Filter = "Excel文件| *.xlsx;*.xls";
                if (saveDialog.ShowDialog() == DialogResult.OK)
                {

                    if (saveDialog.FileName != "")
                    {
                        Microsoft.Office.Interop.Excel.Application excel =
                       new Microsoft.Office.Interop.Excel.Application();//Office引用
                        if (excel == null)
                        {
                            MessageBox.Show("创建Excel对象失败,可能您的电脑尚未安装Excel");
                            return;
                        }

                        Microsoft.Office.Interop.Excel.Workbooks workbooks = excel.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];
                        int colIndex = 0;
                        for (int i = 0; i < DGV2.ColumnCount; i++)
                        {
                            if ((DGV2.Columns[i].Visible && i != DGV2.ColumnCount - 3) || i == DGV2.ColumnCount - 1 || i == DGV2.ColumnCount - 2)//用作于不导出隐藏列
                            {
                                colIndex++;
                                worksheet.Cells[1, colIndex] = DGV2.Columns[i].HeaderText;
                                //worksheet.Cells[1, i] = myDGV.Columns[i].HeaderText;
                            }
                        }
                        for (int r = 0; r < DGV2.Rows.Count; r++)
                        {
                            colIndex = 0;
                            for (int i = 0; i < DGV2.ColumnCount; i++)
                            {
                                if ((DGV2.Columns[i].Visible && i != DGV2.ColumnCount - 3) || i == DGV2.ColumnCount - 1 || i == DGV2.ColumnCount - 2)
                                {
                                    colIndex++;
                                    worksheet.Cells[r + 2, colIndex] = "'" + DGV2.Rows[r].Cells[i].Value;
                                }
                            }
                        }
                        System.Windows.Forms.Application.DoEvents();

                        for (int i = 0; i < 6; i++)
                        {

                            Microsoft.Office.Interop.Excel.Range contentRange = worksheet.Range[worksheet.Cells[1, i + 1], worksheet.Cells[DGV2.RowCount + 1, i + 1]];//不用标题则从第二行开始
                            contentRange.Font.Name = "Consolas";
                            contentRange.Font.Size = 10;
                            contentRange.BorderAround(Microsoft.Office.Interop.Excel.XlLineStyle.xlContinuous, Microsoft.Office.Interop.Excel.XlBorderWeight.xlThick,
                                          Microsoft.Office.Interop.Excel.XlColorIndex.xlColorIndexAutomatic, System.Drawing.Color.Black.ToArgb());
                            contentRange.EntireColumn.AutoFit();
                            //contentRange.HorizontalAlignment = Microsoft.Office.Interop.Excel.XlHAlign.xlHAlignCenter; //水平居中
                            //contentRange.VerticalAlignment = Microsoft.Office.Interop.Excel.XlVAlign.xlVAlignCenter;   //垂直居中
                            contentRange.Borders.LineStyle = Microsoft.Office.Interop.Excel.XlLineStyle.xlContinuous;  //设置边框
                            contentRange.Borders.Weight = Microsoft.Office.Interop.Excel.XlBorderWeight.xlThin;        //边框常规粗细
                            contentRange.WrapText = true;                               //自动换行
                            contentRange.NumberFormatLocal = "@";                       //文本格式

                        }

                        //worksheet.Columns.AutoFit();//列宽自适应
                        //worksheet.Columns.WrapText = true;
                        workbook.SaveAs(saveDialog.FileName);

                        excel.Quit();
                        GC.Collect();
                        MessageBox.Show("导出成功!");

第二种:

                HSSFWorkbook workbook = new HSSFWorkbook();
                DataSet set = new DataSet();
                int iname = 0;
                foreach (DataTable dt in dts)
                {
                    if (dt.TableName == "")
                    {
                        dt.TableName = strname[iname] + (iname + 1).ToString();
                        iname++;
                    }
                    ISheet sheet = workbook.CreateSheet(dt.TableName);
                    ICellStyle HeadercellStyle = workbook.CreateCellStyle();
                    HeadercellStyle.BorderBottom = NPOI.SS.UserModel.BorderStyle.Thin;
                    HeadercellStyle.BorderLeft = NPOI.SS.UserModel.BorderStyle.Thin;
                    HeadercellStyle.BorderRight = NPOI.SS.UserModel.BorderStyle.Thin;
                    HeadercellStyle.BorderTop = NPOI.SS.UserModel.BorderStyle.Thin;
                    HeadercellStyle.Alignment = NPOI.SS.UserModel.HorizontalAlignment.Center;
                    //字体
                    NPOI.SS.UserModel.IFont headerfont = workbook.CreateFont();
                    headerfont.Boldweight = (short)FontBoldWeight.Bold;
                    HeadercellStyle.SetFont(headerfont);


                    //用column name 作为列名
                    int icolIndex = 0;
                    IRow headerRow = sheet.CreateRow(0);
                    foreach (DataColumn item in dt.Columns)
                    {
                        if (item.ToString() == "ID" || item.ToString() == "Name" || item.ToString() == "OAD" || item.ToString() == "Value" || item.ToString() == "ResultAll" || item.ToString() == "Frame")
                        {
                            ICell cell = headerRow.CreateCell(icolIndex);
                            cell.SetCellValue(item.ColumnName);
                            cell.CellStyle = HeadercellStyle;
                            //cell.range.WrapText = true;
                            icolIndex++;
                        }
                    }


                    ICellStyle cellStyle = workbook.CreateCellStyle();
                    //为避免日期格式被Excel自动替换,所以设定 format 为 『@』 表示一率当成text来看
                    cellStyle.DataFormat = HSSFDataFormat.GetBuiltinFormat("@");
                    cellStyle.BorderBottom = NPOI.SS.UserModel.BorderStyle.Thin;
                    cellStyle.BorderLeft = NPOI.SS.UserModel.BorderStyle.Thin;
                    cellStyle.BorderRight = NPOI.SS.UserModel.BorderStyle.Thin;
                    cellStyle.BorderTop = NPOI.SS.UserModel.BorderStyle.Thin;
                    NPOI.SS.UserModel.IFont cellfont = workbook.CreateFont();
                    cellfont.Boldweight = (short)FontBoldWeight.Normal;
                    cellStyle.SetFont(cellfont);

                    //建立内容行
                    int iRowIndex = 1;
                    int iCellIndex = 0;
                    foreach (DataRow Rowitem in dt.Rows)
                    {
                        IRow DataRow = sheet.CreateRow(iRowIndex);
                        foreach (DataColumn Colitem in dt.Columns)
                        {

                            if (Colitem.ToString() == "ID" || Colitem.ToString() == "Name" || Colitem.ToString() == "OAD" || Colitem.ToString() == "Value" || Colitem.ToString() == "ResultAll" || Colitem.ToString() == "Frame")
                            {
                                ICell cell = DataRow.CreateCell(iCellIndex);
                                cell.SetCellValue(Rowitem[Colitem].ToString());
                                cell.CellStyle = cellStyle;
                                cellStyle.WrapText = true;
                                iCellIndex++;
                            }
                        }
                        iCellIndex = 0;
                        iRowIndex++;
                    }
                    //自适应列宽
                    for (int i = 0; i < icolIndex; i++)
                    {
                        sheet.AutoSizeColumn(i);
                    }

                }
                string str = System.AppDomain.CurrentDomain.BaseDirectory;
                //FileStream file = new FileStream(@"D:\" + strExcelFileName + DateTime.Now.ToString("yyyy-MM-dd HHmmss") + ".xlsx", FileMode.OpenOrCreate);
                FileStream file = new FileStream(@str + strExcelFileName + DateTime.Now.ToString("yyyy-MM-dd HH-mm-ss") + ".xlsx", FileMode.OpenOrCreate);
                workbook.Write(file);
                file.Flush();
                file.Close();
                BSave = true;

评论 1
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值