Odio recurrir a StackOverflow por algo tan (aparentemente) básico, pero he estado peleando con Microsoft durante las últimas horas y parece estar llegando a un callejón sin salida. Estoy tratando de leer (grandes) hojas de cálculo Excel 2007+, y Google me ha informado amablemente que el uso del SDK OpenXML es una opción bastante popular. Así que le di una oportunidad a la cosa, leí algunos tutoriales, revisé las páginas de la biblioteca de Microsoft y obtuve muy poco de todas.Usando OpenXmlReader
Estoy usando una pequeña hoja de cálculo de prueba con solo una columna de números y una de cadenas de caracteres; las pruebas a gran escala vendrán después. Probé varias implementaciones similares a la que estoy a punto de publicar, y ninguna de ellas leyó datos. El código siguiente fue tomado principalmente de otro hilo de StackOverflow, donde parecía haber funcionado, no así para mí. Pensé que los verificaría/depuraría/ayudaría con esta versión, porque es probable que esté menos rota que cualquier otra cosa que haya escrito hoy.
static void ReadExcelFileSAX(string fileName)
{
using (SpreadsheetDocument spreadsheetDocument = SpreadsheetDocument.Open(fileName, true))
{
WorkbookPart workbookPart = spreadsheetDocument.WorkbookPart;
WorksheetPart worksheetPart = workbookPart.WorksheetParts.First();
OpenXmlPartReader reader = new OpenXmlPartReader(worksheetPart);
string text;
string rowNum;
while (reader.Read())
{
if (reader.ElementType == typeof(Row))
{
do
{
if (reader.HasAttributes)
{
rowNum = reader.Attributes.First(a => a.LocalName == "r").Value;
Console.Write("rowNum: " + rowNum); //we never even get here, I tested it with a breakpoint
}
} while (reader.ReadNextSibling()); // Skip to the next row
Console.ReadKey();
break; // We just looped through all the rows so no need to continue reading the worksheet
}
if (reader.ElementType == typeof(Cell))
{
}
if (reader.ElementType != typeof(Worksheet)) // Dont' want to skip the contents of the worksheet
reader.Skip(); // Skip contents of any node before finding the first row.
}
reader.Close();
Console.WriteLine();
Console.ReadKey();
}
}
Y, en una nota al margen, ¿hay alguna alternativa al uso del SDK de OpenXml que de alguna manera he pasado por alto?
Pruebe usar la herramienta de productividad Open XML SDK 2.0 disponible aquí: http://www.microsoft.com/en-us/download/details.aspx?id=5124. Le permite abrir cualquier * xlsx * y ver su estructura o ver el código de C# que puede recrear el archivo. De esta forma, puede ver dónde están los valores que desea alcanzar en el archivo con el que está trabajando. –