0

estoy tratando de leer un archivo (pero solo partes de él), estoy usando Interop, pero no consigo iterar entre filas ¿cómo puedo hacerle?

using System;
using Microsoft.Office.Interop.Excel;
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 WindowsFormsApplication1
{

    public partial class Form1 : Form
    {
        Microsoft.Office.Interop.Excel.Application excel;


        Workbook workbook;

        public Form1()
        {
            InitializeComponent();
        }

        private void btnAnalizar_Click(object sender, EventArgs e)
        {
            //Obtener ruta del identificador del documento  
            Worksheet sheet = (Worksheet)workbook.Sheets[1];          
            string id = sheet.Range["A1"].Value2;
            string titulo = sheet.Range["A3"].Value2;



            var numberOfRows = sheet.UsedRange.Columns[3, Type.Missing].Rows.Count;
            var values = sheet.Range["A7:A" + numberOfRows].Value2;
            for (int i = 1; i <= values.Length; i++)
            {
                txt3.Text +=  (values[i, 1] + " ");
            }

            txt1.Text = id;
            txt2.Text = titulo;

        }

        private void btnAbrir_Click(object sender, EventArgs e)
        { 
            DialogResult result = openFileDialog1.ShowDialog();

            if (result == DialogResult.OK)
            {
                string nombre = openFileDialog1.FileName;
                excel = new Microsoft.Office.Interop.Excel.Application();
                workbook = excel.Workbooks.Open(nombre); //Abrir archivo.
                label1.Text = nombre; //Carga la ruta del archivo y la coloca en label1
            }

        }
    }
}

1 respuesta 1

0

Podrias aplicar la tecnica del articulo

Read Excel File in C#

Excel._Worksheet xlWorksheet = xlWorkbook.Sheets[1];
Excel.Range xlRange = xlWorksheet.UsedRange;

En este caso hace uso del UsedRange para definir el rango que itera, pero podrias definir uno distinto

Excel.Range xlRange = xlWorksheet.Range["A1", "C10"];

pero obtienes el range no el value

int rowCount = xlRange.Rows.Count;
int colCount = xlRange.Columns.Count;

List<string> lista = new List<string>();
for (int i = 1; i <= rowCount; i++)
{
    for (int j = 1; j <= colCount; j++)
    {
        lista.Add(xlRange.Cells[i, j].Value2);
    }
 }

 TextBox3.Text = string.Join(", ", lista);

Tu Respuesta

Al pulsar en “Publica tu respuesta”, muestras tu consentimiento a nuestros términos de servicio, política de privacidad y política de cookies

¿No es la respuesta que buscas? Examina otras preguntas con la etiqueta o formula tu propia pregunta.