using Microsoft.Office.Interop.Excel; using System; using System.Collections.Generic; using System.ComponentModel; using System.Data; using System.Drawing; using System.Linq; using System.Text; using System.Threading.Tasks; using System.Windows.Forms; namespace WindowsFormsWordExcelDemo { public partial class Excel : Form { public Excel() { InitializeComponent(); } private void 打开ToolStripMenuItem_Click(object sender, EventArgs e) { OpenFileDialog openFileDialog = new OpenFileDialog(); openFileDialog.Filter = "Excel Files(*.xlsx)|*.xlsx|Excel Files(*.xls)|*.xls"; if (openFileDialog.ShowDialog() == DialogResult.OK) { Microsoft.Office.Interop.Excel.Application excel = new Microsoft.Office.Interop.Excel.Application(); Workbook workbook = excel.Workbooks.Add(openFileDialog.FileName); Worksheet worksheet = workbook.ActiveSheet;//让工作表等于当前打开的工作表 //写 worksheet.Range[worksheet.Cells[1, 1], worksheet.Cells[1, 1]] = "hello world"; //合并单元格 //Range titleRange = worksheet.Range[worksheet.Cells[1, 1], worksheet.Cells[1, 5]]; //titleRange.Merge(); excel.Visible = true;//使用默认程序打开Excel int cols = worksheet.Columns.Count; int rows = worksheet.Rows.Count; //读取行,索引从1开始 for(int i = 1; i <= rows; i++) { //读取列 for(int j = 1; j <= cols; j++) { if (worksheet.Range[worksheet.Cells[i, j], worksheet.Cells[i, j]] != null && worksheet.Range[worksheet.Cells[i, j], worksheet.Cells[i, j]].Text != String.Empty) { //两个worksheet.Cells[i,j],第一个表示起始单元格,第二个表示结束单元格 //richTextBox1.Text = richTextBox1.Text + worksheet.Range[worksheet.Cells[i,j], worksheet.Cells[i,j]].Value.ToString()+"\n"; richTextBox1.Text = richTextBox1.Text + "\n" + worksheet.Range[worksheet.Cells[i, j], worksheet.Cells[i, j]].Text; } else { break; } } } MessageBox.Show("完成"); workbook.Close(); excel.Quit(); } } } }