永发信息网

C# winform 中如何导入Excel

答案:2  悬赏:70  手机版
解决时间 2021-08-11 23:02
  • 提问者网友:我的未来我做主
  • 2021-08-10 22:53
C# winform 中如何导入Excel
最佳答案
  • 五星知识达人网友:独行浪子会拥风
  • 2021-08-10 23:29

你是要从excel中导入数据到winform吗?如果是这样,可以这样:


引用office11.0组件后,


 Microsoft.Office.Interop.Excel.Application application; //这是一个客户端
    Microsoft.Office.Interop.Excel.Workbooks workbooks; //所有工作薄
    Microsoft.Office.Interop.Excel.Worksheet worksheet;//工作表
    Microsoft.Office.Interop.Excel.Workbook workbook; //所用到的工作表


    void IsRunEX()


{  


    OpenFileDialog openfilediaglog = new OpenFileDialog();
    openfilediaglog.Filter = "xls文件|*.xls";
    if (openfilediaglog.ShowDialog() == DialogResult.OK)
    {
    FieldName = openfilediaglog.FileName;
    application = new Microsoft.Office.Interop.Excel.Application();
    workbooks = application.Workbooks;
    workbook = returnworkbook(FieldName, workbooks);
    worksheet = (Microsoft.Office.Interop.Excel.Worksheet)workbook.Sheets[1];  //选择第一个表
    Range range = worksheet.Cells[1, 8] as Range; //这是选择第一行第八列的内容
    Range rangee = worksheet.Cells[1, 9] as Range; //这是第一行到九列的内容


    string str1=range.Value2.ToString();


    string str2=ragee.Value2.ToString();


    ...................  //你所要做的操作


    ..................


    workbook.Close(Type.Missing, FieldName, Type.Missing);
    workbooks.Close();    //退出关闭资源
    application.Quit();


    }
}


 private Workbook returnworkbook(string filename,Workbooks works)  //这里是打一开一个工作表
    {
    Microsoft.Office.Interop.Excel.Workbook wk=works.Open(
    filename, Type.Missing, Type.Missing,
    Type.Missing, Type.Missing, Type.Missing, Type.Missing, Type.Missing,
    Type.Missing, Type.Missing, Type.Missing, Type.Missing, Type.Missing,
    Type.Missing, Type.Missing);
    return wk;
    }

全部回答
  • 1楼网友:不如潦草
  • 2021-08-10 23:39

准确说是把DataTable导出Excel:通用算法:

public static void ExportExcel(DataTable eDataTable)      {     try     {     Excel.ApplicationClass ExcelApp;     ExcelApp = new Excel.ApplicationClass();     Excel.Workbook ExcelBook = ExcelApp.Workbooks.Add(1);     Excel.Worksheet ExcelSheet = (Excel.Worksheet)ExcelBook.Worksheets[1];     ExcelApp.Visible = true;     //写列标题     for (int i = 0; i < eDataTable.Columns.Count; i++)     {     ExcelSheet.Cells[1, i + 1] = eDataTable.Columns[i].ColumnName;     }     //写值     for (int r = 0; r < eDataTable.Rows.Count; r++)     {     for (int i = 0; i < eDataTable.Columns.Count; i++)     {     ExcelSheet.Cells[r + 2, i + 1] = eDataTable.Rows[r][i];     }     }     }     catch (Exception ex)     {     ErrLog.ExcelErr(ex.ToString());     }     finally     {     GC.Collect();     }     }

我要举报
如以上回答内容为低俗、色情、不良、暴力、侵权、涉及违法等信息,可以点下面链接进行举报!
点此我要举报以上问答信息
大家都在看
推荐资讯