数据导入到EXCEL(EXCELHelper)

using System;
using System.Data;
using System.IO;
using System.Windows.Forms;
using Microsoft.Office.Interop.Excel;


namespace zzz.BusinessSystem
{
    public static class ExcelHelp
    {
        


       
        /// <summary>
        /// DataTable导出到Excel,效率比较慢,是正常格式的Excel
        /// </summary>
        /// <param name="dt"> DataTable对象</param>
        /// <param name="FileName">文件路径+文件名 (例如:"E:\\aa.xlsx")</param>
        public static void DataTable_Excel(System.Data.DataTable dt, string FileName)
        {
            if (dt == null)
                return;
            int rowNumber = dt.Rows.Count;
            int columnNumber = dt.Columns.Count;
            int rowIndex = 1;
            int columnIndex = 0;
            Microsoft.Office.Interop.Excel.Application xlApp = new Microsoft.Office.Interop.Excel.Application();
            //System.Windows.Forms.Application xlapp = new System.Windows.Forms.Application();


            xlApp.DefaultFilePath = "";
            xlApp.DisplayAlerts = true;
            xlApp.SheetsInNewWorkbook = 1;
            Workbook xlBook = xlApp.Workbooks.Add(true);
            //将DataTable的列明导入Excel的第一行
            foreach (DataColumn dc in dt.Columns)
            {
                columnIndex++;
                xlApp.Cells[rowIndex, columnIndex] = dc.ColumnName;
            }


            //
            for (int i = 0; i < rowNumber; i++)
            {
                rowIndex++;
                columnIndex = 0;
                for (int j = 0; j < columnNumber; j++)
                {
                    columnIndex++;
                    xlApp.Cells[rowIndex, columnIndex] = dt.Rows[i][j].ToString();
                }
            }


            //xlSheet.SaveAs(Page.Server.MapPath(".") & "\ExcelFolder\download.xls")
            xlBook.SaveAs(FileName);
        }




        #region winform 导出
        public static void win_DataTabletoExcel(System.Data.DataTable tmpDataTable, string strFileName)
        {


            if (tmpDataTable == null)


                return;


            int rowNum = tmpDataTable.Rows.Count;


            int columnNum = tmpDataTable.Columns.Count;


            int rowIndex = 1;


            int columnIndex = 0;






            Microsoft.Office.Interop.Excel.Application xlApp = new Microsoft.Office.Interop.Excel.Application();


            xlApp.DefaultFilePath = "";


            xlApp.DisplayAlerts = true;


            xlApp.SheetsInNewWorkbook = 1;


            Workbook xlBook = xlApp.Workbooks.Add(true);






            //将DataTable的列名导入Excel表第一行


            foreach (DataColumn dc in tmpDataTable.Columns)
            {


                columnIndex++;


                xlApp.Cells[rowIndex, columnIndex] = dc.ColumnName;


            }






            //将DataTable中的数据导入Excel中


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


                rowIndex++;


                columnIndex = 0;


                for (int j = 0; j < columnNum; j++)
                {


                    columnIndex++;


                    xlApp.Cells[rowIndex, columnIndex] = tmpDataTable.Rows[i][j].ToString();


                }


            }


            //xlBook.SaveCopyAs(HttpUtility.UrlDecode(strFileName, System.Text.Encoding.UTF8));


            xlBook.SaveCopyAs(strFileName);


        }


        public static void Win_DataTableToExcel(System.Data.DataTable dt, string saveFileName)
        {
            if (dt == null) return;
            //-***************获取excel对象***************
            //  string saveFileName = "";
            TimeSpan dateBegin = new TimeSpan(DateTime.Now.Ticks);
            bool fileSaved = false;
            SaveFileDialog saveDialog = new SaveFileDialog();
            saveDialog.DefaultExt = "xls";
            saveDialog.Filter = "Excel文件|*.xls";
            saveDialog.FileName = "导入记录查询结果 " + DateTime.Today.ToString("yyyy-MM-dd");
            saveDialog.ShowDialog();
            saveFileName = saveDialog.FileName;
            if (saveFileName.IndexOf(":") < 0) return; //被点了取消
            Microsoft.Office.Interop.Excel.Application xlApp = new Microsoft.Office.Interop.Excel.Application();
            if (xlApp == null)
            {
                MessageBox.Show("无法启动Excel,可能您未安装Excel");
                return;
            }
            Microsoft.Office.Interop.Excel.Workbook workbook = xlApp.Workbooks.Add(true);
            Microsoft.Office.Interop.Excel.Worksheet worksheet = (Microsoft.Office.Interop.Excel.Worksheet)workbook.Worksheets[1];
            Microsoft.Office.Interop.Excel.Range range;




            // 列索引,行索引,总列数,总行数                   
            int colIndex = 0;
            int RowIndex = 0;
            int colCount = dt.Columns.Count;
            int RowCount = dt.Rows.Count;




            // *****************获取数据*********************
            //dataGrid1.CaptionVisible = true;
            //dataGrid1.CaptionText = "正在导出数据";
            // 创建缓存数据
            object[,] objData = new object[RowCount + 1, colCount];
            // 获取列标题
            for (int i = 0; i < dt.Columns.Count; i++)
            {
                objData[RowIndex, colIndex++] = dt.Columns[i].Caption; // dgv.Columns[i].HeaderText;
            }


            // 获取具体数据
            for (RowIndex = 1; RowIndex < RowCount; RowIndex++)
            {
                for (colIndex = 0; colIndex < colCount; colIndex++)
                {
                    objData[RowIndex, colIndex] = dt.Rows[RowIndex - 1][colIndex];
                }


            }


            //********************* 写入Excel*******************


            //range = worksheet.get_Range(xlApp.Cells[2, 1], xlApp.Cells[RowCount, colCount]);
            //range.Value2 = objData;


            range = worksheet.Range[xlApp.Cells[2, 1], xlApp.Cells[RowCount + 1, colCount]];
            range.Value = objData;




            System.Windows.Forms.Application.DoEvents();


            //*******************设置输出格式******************************


            //设置顶部説明   合并的单元格
            range = worksheet.get_Range(xlApp.Cells[1, 1], xlApp.Cells[1, colCount]);
            range.MergeCells = true;
            range.RowHeight = 38;
            range.Font.Bold = true;
            range.Font.Size = 14;
            range.Font.ColorIndex = 10;//字体颜色
            xlApp.ActiveCell.FormulaR1C1 = "导入记录查询结果";


            //特殊数字格式
            range = worksheet.get_Range(xlApp.Cells[2, colCount], xlApp.Cells[RowCount, colCount]);
            // range.NumberFormat = "yyyy-MM-dd hh:mm:ss";


            xlApp.Cells.HorizontalAlignment = Microsoft.Office.Interop.Excel.Constants.xlCenter;
            range = worksheet.get_Range(xlApp.Cells[2, 1], xlApp.Cells[2, colCount]);
            //  range.Interior.ColorIndex = 10;//背景色
            range.Font.Bold = true;
            range.RowHeight = 20;
   
            if (saveFileName != "")
            {
                try
                {
                    workbook.Saved = true;
                    workbook.SaveCopyAs(saveFileName);
                    fileSaved = true;
                }
                catch (Exception ex)
                {
                    fileSaved = false;
                    MessageBox.Show("导出文件时出错,文件可能正被打开!\n" + ex.Message);
                }
            }
            else
            {
                fileSaved = false;
            }
            xlApp.Quit();
            GC.Collect();//强行销毁   


            TimeSpan dateEnd = new TimeSpan(DateTime.Now.Ticks);
            TimeSpan tspan = dateBegin.Subtract(dateEnd).Duration();
            MessageBox.Show("导出成功,用时" + tspan.ToString() + "秒");
            if (fileSaved && System.IO.File.Exists(saveFileName))
                System.Diagnostics.Process.Start(saveFileName); //保存成功后打开此文件
        }


        public static void Win_ExportExcel(System.Data.DataTable dt, string fileName)
        {
            if (dt == null) return;
            string saveFileName = "";
            bool fileSaved = false;
            SaveFileDialog saveDialog = new SaveFileDialog();
            saveDialog.DefaultExt = "xls";
            saveDialog.Filter = "Excel文件|*.xls";
            saveDialog.FileName = fileName + DateTime.Now.ToString("yyyyMMddhhmmss");
            saveDialog.ShowDialog();
            saveFileName = saveDialog.FileName;
            if (saveFileName.IndexOf(":") < 0) return; //被点了取消  
            Microsoft.Office.Interop.Excel.Application xlApp = new Microsoft.Office.Interop.Excel.Application();
            if (xlApp == null)
            {
                MessageBox.Show("无法创建Excel对象,可能您的机子未安装Excel");
                return;
            }


            Workbooks workbooks = xlApp.Workbooks;


            Workbook workbook = workbooks.Add(XlWBATemplate.xlWBATWorksheet);
            Worksheet worksheet = (Worksheet)workbook.Worksheets[1];//取得sheet1  
            Range range;
            string oldCaption = DateTime.Now.ToString("yyyy-MM-dd");
            long totalCount = dt.Rows.Count;
            long rowRead = 0;
            float percent = 0;
            worksheet.Cells[1, 1] = DateTime.Now.ToString("yyyy-MM-dd");
            //写入字段  
            for (int i = 0; i < dt.Columns.Count; i++)
            {
                worksheet.Cells[2, i + 1] = dt.Columns[i].ColumnName;
                range = (Range)worksheet.Cells[2, i + 1];
                range.Interior.ColorIndex = 15;
                range.Font.Bold = true;
            }
            //写入数值  
            for (int r = 0; r < dt.Rows.Count; r++)
            {
                for (int i = 0; i < dt.Columns.Count; i++)
                {
                    if (dt.Rows[r][i].GetType().FullName == "System.DateTime")
                    {
                        worksheet.Cells[r + 3, i + 1] = dt.Rows[r][i].ToString();
                    }
                    else
                    {
                        worksheet.Cells[r + 3, i + 1] = dt.Rows[r][i];
                    }
                }
                rowRead++;
                percent = ((float)(100 * rowRead)) / totalCount;
                //this.lbl_process.Text = "正在导出数据[" + percent.ToString("0.00") + "%]..."; //这里可以自己做一个label用来显示进度.  
                System.Windows.Forms.Application.DoEvents();
            }
            //this.lbl_process.Visible = false;


            range = worksheet.Range[worksheet.Cells[2, 1], worksheet.Cells[dt.Rows.Count + 2, dt.Columns.Count]];
            range.BorderAround(XlLineStyle.xlContinuous, XlBorderWeight.xlThin, XlColorIndex.xlColorIndexAutomatic, null);
            range.Borders[XlBordersIndex.xlInsideHorizontal].ColorIndex = XlColorIndex.xlColorIndexAutomatic;
            range.Borders[XlBordersIndex.xlInsideHorizontal].LineStyle = XlLineStyle.xlContinuous;
            range.Borders[XlBordersIndex.xlInsideHorizontal].Weight = XlBorderWeight.xlThin;
            if (dt.Columns.Count > 1)
            {
                range.Borders[XlBordersIndex.xlInsideVertical].ColorIndex = XlColorIndex.xlColorIndexAutomatic;
                range.Borders[XlBordersIndex.xlInsideVertical].LineStyle = XlLineStyle.xlContinuous;
                range.Borders[XlBordersIndex.xlInsideVertical].Weight = XlBorderWeight.xlThin;
            }
            if (saveFileName != "")
            {
                try
                {
                    workbook.Saved = true;
                    workbook.SaveCopyAs(saveFileName);
                    fileSaved = true;
                }
                catch (Exception ex)
                {
                    fileSaved = false;
                    MessageBox.Show("导出文件时出错,文件可能正被打开!\n" + ex.Message);
                }
            }
            else
            {
                fileSaved = false;


            }


            xlApp.Quit();


            GC.Collect();//强行销毁  


            if (fileSaved && File.Exists(saveFileName))
            {


                //System.Diagnostics.Process.Start(saveFileName);  


                MessageBox.Show("数据导出成功!", "美承零售系统");


            }


        }


        public static void Win_DataGridViewToExcel(DataGridView dgv)
        {
            SaveFileDialog dlg = new SaveFileDialog();
            string saveFileName = "";
            bool fileSaved = false;
            dlg.Filter = "Execl files (*.xls)|*.xls";
            dlg.FilterIndex = 0;
            dlg.RestoreDirectory = true;
            dlg.CreatePrompt = true;
            dlg.Title = "保存为Excel文件";
            dlg.FileName = "导出数据" + DateTime.Now.ToString("yyyyMMddhhmmss");






            Microsoft.Office.Interop.Excel.Application xlApp = new Microsoft.Office.Interop.Excel.Application();
            if (xlApp == null)
            {
                MessageBox.Show("无法创建Excel对象,可能您的机子未安装Excel");
                return;
            }
            if (dgv.Rows.Count == 0)
                return;


            if (dlg.ShowDialog() == DialogResult.OK)
            {
                saveFileName = dlg.FileName;
                if (saveFileName.IndexOf(":") < 0) return; //被点了取消  
                Stream myStream;
                myStream = dlg.OpenFile();
                StreamWriter sw = new StreamWriter(myStream, System.Text.Encoding.GetEncoding(-0));
                string columnTitle = "";
                try
                {
                    //写入列标题   
                    for (int i = 0; i < dgv.ColumnCount; i++)
                    {
                        if (dgv.Columns[i].Visible == true)
                        {
                            if (i > 0)
                            {
                                columnTitle += "\t";
                            }
                            columnTitle += dgv.Columns[i].HeaderText;
                        }
                    }
                    sw.WriteLine(columnTitle);


                    //写入列内容   
                    for (int j = 0; j < dgv.Rows.Count; j++)
                    {
                        string columnValue = "";
                        for (int k = 0; k < dgv.Columns.Count; k++)
                        {
                            if (dgv.Columns[k].Visible == true)
                            {
                                if (k > 0)
                                {
                                    columnValue += "\t";
                                }
                                if (dgv.Rows[j].Cells[k].Value == null)
                                    columnValue += "";
                                else
                                    columnValue += dgv.Rows[j].Cells[k].Value.ToString().Trim();
                            }
                        }
                        sw.WriteLine(columnValue);
                    }
                    fileSaved = true;
                }
                catch (Exception e)
                {
                    fileSaved = false;
                    MessageBox.Show(e.ToString(), "美承零售系统", MessageBoxButtons.OK, MessageBoxIcon.Asterisk);
                }
                finally
                {
                    sw.Close();
                    myStream.Close();
                }




                if (fileSaved && File.Exists(saveFileName))
                {
                    MessageBox.Show("数据导出成功!", "美承零售系统", MessageBoxButtons.OK, MessageBoxIcon.Asterisk);
                }
            }
        }


        /// <summary>
        /// 到处数据 lihui
        /// </summary>
        /// <param name="dt"></param>
        /// <param name="strFileName"></param>
        public static void Win_DataTabletoExcel1(System.Data.DataTable dt, string strFileName)
        {
            if (dt == null) return;


            SaveFileDialog saveDialog = new SaveFileDialog();
            saveDialog.DefaultExt = "xls";
            saveDialog.Filter = "Excel文件|*.xls";
            saveDialog.FileName = strFileName + DateTime.Now.ToString("yyyyMMddhhmmss");
            if (saveDialog.ShowDialog() == DialogResult.Cancel)
            {
                return;
            }


            string saveFileName = "";
            bool fileSaved = false;
            
            Microsoft.Office.Interop.Excel.Application xlApp;
            Workbooks workbooks;
            Workbook workbook;
            Worksheet worksheet;
            Range range;


            saveFileName = saveDialog.FileName;


            xlApp = new Microsoft.Office.Interop.Excel.Application();
            if (xlApp == null)
            {
                MessageBox.Show("无法创建Excel对象,可能您的机器未安装Excel");
                return;
            }


            workbooks = xlApp.Workbooks;
            workbook = workbooks.Add(XlWBATemplate.xlWBATWorksheet);
            worksheet = (Worksheet)workbook.Worksheets[1];//取得sheet1  
            
           // string oldCaption = DateTime.Now.ToString("yyyy-MM-dd");
            long totalCount = dt.Rows.Count;
            long rowRead = 0;
            float percent = 0;
            worksheet.Cells[1, 1] = string.Format("日期:{0}",DateTime.Now.ToString("yyyy-MM-dd"));
            //写入字段  
            for (int i = 0; i < dt.Columns.Count; i++)
            {
                worksheet.Cells[2, i + 1] = dt.Columns[i].ColumnName;
                range = (Range)worksheet.Cells[2, i + 1];
                range.Interior.ColorIndex = 15;
                range.Font.Bold = true;
            }
            //写入数值  
            for (int r = 0; r < dt.Rows.Count; r++)
            {
                for (int i = 0; i < dt.Columns.Count; i++)
                {
                    if (dt.Rows[r][i].GetType().FullName == "System.DateTime")
                    {
                        worksheet.Cells[r + 3, i + 1] = dt.Rows[r][i].ToString();
                    }
                    else
                    {
                        range = (Range)worksheet.Cells[r + 3, i + 1];
                        range.NumberFormat = "@";
                        worksheet.Cells[r + 3, i + 1] = dt.Rows[r][i];
                    }
                }
                rowRead++;
                percent = ((float)(100 * rowRead)) / totalCount;
                System.Windows.Forms.Application.DoEvents();
            }
            range = worksheet.Range[worksheet.Cells[2, 1], worksheet.Cells[dt.Rows.Count + 2, dt.Columns.Count]];
            range.BorderAround(XlLineStyle.xlContinuous, XlBorderWeight.xlThin, XlColorIndex.xlColorIndexAutomatic, null);
            range.Borders[XlBordersIndex.xlInsideHorizontal].ColorIndex = XlColorIndex.xlColorIndexAutomatic;
            range.Borders[XlBordersIndex.xlInsideHorizontal].LineStyle = XlLineStyle.xlContinuous;
            range.Borders[XlBordersIndex.xlInsideHorizontal].Weight = XlBorderWeight.xlThin;
            if (dt.Columns.Count > 1)
            {
                range.Borders[XlBordersIndex.xlInsideVertical].ColorIndex = XlColorIndex.xlColorIndexAutomatic;
                range.Borders[XlBordersIndex.xlInsideVertical].LineStyle = XlLineStyle.xlContinuous;
                range.Borders[XlBordersIndex.xlInsideVertical].Weight = XlBorderWeight.xlThin;
            }
            if (saveFileName != "")
            {
                try
                {
                    workbook.Saved = true;
                    workbook.SaveCopyAs(saveFileName);
                    fileSaved = true;
                }
                catch (Exception ex)
                {
                    fileSaved = false;
                    MessageBox.Show("导出文件时出错,文件可能正被打开!\n" + ex.Message);
                }
            }
            else
            {
                fileSaved = false;


            }


            xlApp.Quit();


            GC.Collect();//强行销毁  


            if (fileSaved && File.Exists(saveFileName))
            {
                MessageBox.Show("数据导出成功!", "美承零售系统");
            }
        }


        /// <summary>
        /// 导出无标题数据 周吉敏---销售发票列表中导出出库明细
        /// </summary>
        /// <param name="dt"></param>
        /// <param name="strFileName"></param>
        public static void Win_StocktoExcel(System.Data.DataTable dt, string strFileName)
        {
            if (dt == null) return;


            SaveFileDialog saveDialog = new SaveFileDialog();
            saveDialog.DefaultExt = "xls";
            saveDialog.Filter = "Excel文件|*.xls";
            saveDialog.FileName = strFileName;
            if (saveDialog.ShowDialog() == DialogResult.Cancel)
            {
                return;
            }


            string saveFileName = "";
            bool fileSaved = false;


            Microsoft.Office.Interop.Excel.Application xlApp;
            Workbooks workbooks;
            Workbook workbook;
            Worksheet worksheet;
            Range range;


            saveFileName = saveDialog.FileName;


            xlApp = new Microsoft.Office.Interop.Excel.Application();
            if (xlApp == null)
            {
                MessageBox.Show("无法创建Excel对象,可能您的机器未安装Excel");
                return;
            }


            workbooks = xlApp.Workbooks;
            workbook = workbooks.Add(XlWBATemplate.xlWBATWorksheet);
            worksheet = (Worksheet)workbook.Worksheets[1];//取得sheet1  


            // string oldCaption = DateTime.Now.ToString("yyyy-MM-dd");
            long totalCount = dt.Rows.Count;
            long rowRead = 0;
            float percent = 0;
           // worksheet.Cells[1, 1] = string.Format("日期:{0}", DateTime.Now.ToString("yyyy-MM-dd"));
            //写入字段  
            for (int i = 0; i < dt.Columns.Count; i++)
            {
                worksheet.Cells[1, i + 1] = dt.Columns[i].ColumnName;
                range = (Range)worksheet.Cells[1, i + 1];
                range.Interior.ColorIndex = 15;
                range.Font.Bold = true;
            }
            //写入数值  
            for (int r = 0; r < dt.Rows.Count; r++)
            {
                for (int i = 0; i < dt.Columns.Count; i++)
                {
                    if (dt.Rows[r][i].GetType().FullName == "System.DateTime")
                    {
                        worksheet.Cells[r + 2, i + 1] = dt.Rows[r][i].ToString();
                    }
                    else
                    {
                        range = (Range)worksheet.Cells[r + 2, i + 1];
                        range.NumberFormat = "@";
                        worksheet.Cells[r + 2, i + 1] = dt.Rows[r][i];
                    }
                }
                rowRead++;
                percent = ((float)(100 * rowRead)) / totalCount;
                System.Windows.Forms.Application.DoEvents();
            }
            range = worksheet.Range[worksheet.Cells[2, 1], worksheet.Cells[dt.Rows.Count + 1, dt.Columns.Count]];
            range.BorderAround(XlLineStyle.xlContinuous, XlBorderWeight.xlThin, XlColorIndex.xlColorIndexAutomatic, null);
            range.Borders[XlBordersIndex.xlInsideHorizontal].ColorIndex = XlColorIndex.xlColorIndexAutomatic;
            range.Borders[XlBordersIndex.xlInsideHorizontal].LineStyle = XlLineStyle.xlContinuous;
            range.Borders[XlBordersIndex.xlInsideHorizontal].Weight = XlBorderWeight.xlThin;
            if (dt.Columns.Count > 1)
            {
                range.Borders[XlBordersIndex.xlInsideVertical].ColorIndex = XlColorIndex.xlColorIndexAutomatic;
                range.Borders[XlBordersIndex.xlInsideVertical].LineStyle = XlLineStyle.xlContinuous;
                range.Borders[XlBordersIndex.xlInsideVertical].Weight = XlBorderWeight.xlThin;
            }
            if (saveFileName != "")
            {
                try
                {
                    workbook.Saved = true;
                    workbook.SaveCopyAs(saveFileName);
                    fileSaved = true;
                }
                catch (Exception ex)
                {
                    fileSaved = false;
                    MessageBox.Show("导出文件时出错,文件可能正被打开!\n" + ex.Message);
                }
            }
            else
            {
                fileSaved = false;


            }


            xlApp.Quit();


            GC.Collect();//强行销毁  


            if (fileSaved && File.Exists(saveFileName))
            {
                MessageBox.Show("数据导出成功!", "美承进销存系统");
            }
        }


        #endregion
    }
}
  • 0
    点赞
  • 1
    收藏
    觉得还不错? 一键收藏
  • 0
    评论
可以使用以下步骤实现MVC+bootstrap实现Excel导入功能: 1. 在MVC项目中添加ExcelHelper类,用于读取Excel内容。 2. 在View视图中添加导入Excel的按钮和相关表单控件。 3. 在Controller中添加导入Excel文件的Action方法,通过HttpPostedFileBase参数获取上传的Excel文件。 4. 在Action方法中调用ExcelHelper类读取Excel内容,并将读取结果存储到Model中。 5. 在View视图中展示读取结果。 6. 使用Bootstrap的样式美化展示效果。 具体实现细节可以参考以下示例代码: ExcelHelper类: ```csharp public class ExcelHelper { public static DataTable ReadExcelFile(Stream stream) { IWorkbook workbook = null; ISheet sheet = null; DataTable data = new DataTable(); int startRow = 0; try { workbook = WorkbookFactory.Create(stream); sheet = workbook.GetSheetAt(0); if (sheet != null) { IRow firstRow = sheet.GetRow(0); int cellCount = firstRow.LastCellNum; for (int i = firstRow.FirstCellNum; i < cellCount; ++i) { DataColumn column = new DataColumn(firstRow.GetCell(i).StringCellValue); data.Columns.Add(column); } startRow = sheet.FirstRowNum + 1; for (int i = startRow; i <= sheet.LastRowNum; ++i) { IRow row = sheet.GetRow(i); if (row == null) continue; DataRow dataRow = data.NewRow(); for (int j = row.FirstCellNum; j < cellCount; ++j) { if (row.GetCell(j) != null) dataRow[j] = row.GetCell(j).ToString(); } data.Rows.Add(dataRow); } } } catch (Exception ex) { throw ex; } finally { sheet?.Dispose(); workbook?.Close(); } return data; } } ``` View视图: ```html @using (Html.BeginForm("Import", "Excel", FormMethod.Post, new { enctype = "multipart/form-data" })) { <div class="form-group"> <label for="ExcelFile">选择Excel文件</label> <input type="file" name="ExcelFile" id="ExcelFile" class="form-control-file" accept=".xls,.xlsx"> </div> <button type="submit" class="btn btn-primary">导入</button> } @if (Model != null && Model.Rows.Count > 0) { <table class="table table-striped"> <thead> <tr> @foreach (DataColumn column in Model.Columns) { <th>@column.ColumnName</th> } </tr> </thead> <tbody> @foreach (DataRow row in Model.Rows) { <tr> @foreach (DataColumn column in Model.Columns) { <td>@row[column.ColumnName]</td> } </tr> } </tbody> </table> } ``` Controller: ```csharp public class ExcelController : Controller { public ActionResult Index() { return View(); } [HttpPost] public ActionResult Import(HttpPostedFileBase ExcelFile) { if (ExcelFile != null && ExcelFile.ContentLength > 0) { try { DataTable data = ExcelHelper.ReadExcelFile(ExcelFile.InputStream); return View(data); } catch (Exception ex) { ModelState.AddModelError("ExcelFile", "读取Excel文件时发生错误:" + ex.Message); } } else { ModelState.AddModelError("ExcelFile", "请选择Excel文件!"); } return View(); } } ``` 以上示例代码中,上传的Excel文件将通过HttpPostedFileBase参数传递到Controller的Import方法中,然后调用ExcelHelper类的ReadExcelFile方法读取Excel内容,并将读取结果存储到Model中,在View视图中展示读取结果。同时,使用Bootstrap的样式美化展示效果。

“相关推荐”对你有帮助么?

  • 非常没帮助
  • 没帮助
  • 一般
  • 有帮助
  • 非常有帮助
提交
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值