C# winform 中如何导入Excel
- 提问者网友:我的未来我做主
- 2021-08-10 22:53
- 五星知识达人网友:独行浪子会拥风
- 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(); } }