Leggi i dati da XLSX in C#
Domanda
Sono nuovo in C# e sto cercando di leggere un file XLSX in C# con il seguente codice:
string Connection = "Provider=Microsoft.ACE.OLEDB.12.0;DataSource=c:\\Temp\\source.xlsx;Extended Properties=\"Excel 12.0;HDR=Yes;IMEX=1\";";
//code to read the content of format file
OleDbConnection con = new OleDbConnection(Connection);
OleDbCommand command = new OleDbCommand();
DataTable dt = new DataTable();
OleDbDataAdapter myCommand = new OleDbDataAdapter("select * from [Tabelle1$]", con);
myCommand.Fill(dt);
Console.Write(dt.Rows.Count);
Ottengo il conteggio corretto dall'output, ma ho altre 2 domande:
1.Come fai una dichiarazione selezionata (come accedere alle righe)?
select * from [Tabelle1$] where A = '123' (A being an existing Excel row)
lancerà un errore menzionando parametri errati ...
2. Qualcuno può fornirmi un collegamento tutorial o un campione breve Come accedere ai dati?
Soluzione
Si prega di fare riferimento al seguente codice di esempio:
private DataTable LoadXLS(string strFile, String sheetName, String column, String value)
{
DataTable dtXLS = new DataTable(sheetName);
try
{
string strConnectionString = "";
if(strFile.Trim().EndsWith(".xlsx")) {
strConnectionString = string.Format("Provider=Microsoft.ACE.OLEDB.12.0;Data Source={0};Extended Properties=\"Excel 12.0 Xml;HDR=YES;IMEX=1\";", strFile);
} else if(strFile.Trim().EndsWith(".xls")) {
strConnectionString = string.Format("Provider=Microsoft.Jet.OLEDB.4.0;Data Source={0};Extended Properties=\"Excel 8.0;HDR=Yes;IMEX=1\";", strFile);
}
OleDbConnection SQLConn = new OleDbConnection(strConnectionString);
SQLConn.Open();
OleDbDataAdapter SQLAdapter = new OleDbDataAdapter();
string sql = "SELECT * FROM [" + sheetName + "$] WHERE " + column + " = " + value;
OleDbCommand selectCMD = new OleDbCommand(sql, SQLConn);
SQLAdapter.SelectCommand = selectCMD;
SQLAdapter.Fill(dtXLS);
SQLConn.Close();
}
catch (Exception e)
{
Console.WriteLine(e.ToString());
}
return dtXLS;
}
Altri suggerimenti
Personalmente, ho trovato la lettura di fogli di calcolo Excel con OledBConnections difficile da lavorare; Quindi vorrei offrire un grande open source e gratis Excelmapper alternativa.
Fornisce un modo molto più conciso (cioè leggibile) di leggere i file Excel rispetto alle query OLE.
1. Dato un file Excel:
2. Creare una persona C# oggetto:
public class Person
{
public string FirstName { get; set; }
public string LastName { get; set; }
public string Email { get; set; }
}
3. Leggilo usando ExcelMapper
var fileName = @"C:\Temp\Names.xlsx"; // your excel file
List<Person> people = new ExcelMapper(fileName).Fetch<Person>();
Puoi anche leggere da altri fogli di lavoro, semplicemente passando un argomento aggiuntivo:
var fileName = @"C:\Temp\Names.xlsx"; // your excel file
List<Person> people = new ExcelMapper(fileName).Fetch<Person>("Sheet2");
È possibile installarlo usando Nuget
Install-Package ExcelMapper
Disclaimer: Non sono associato a Excelmapper, ma dopo aver provato varie biblioteche diverse, ho trovato questa biblioteca con cui lavorare più facile.
Reg: "2. Qualcuno può fornirmi un collegamento tutorial o un campione breve come accedere ai dati"
Ecco un breve video in mostra quanto sopra.
So che questa è una vecchia domanda con un'ottima risposta, ma questa pagina è arrivata in alto sui risultati di Google per "Importa XLSX C#", quindi volevo aggiungere un modo più moderno e semplice per leggere i dati XLS/XLSX utilizzando la libreria NPOI. Voglio assicurarmi che nuovi sviluppatori C# sappiano che esiste un modo più semplice per importare dati Excel anziché utilizzare ADO.NET.
Uso una combinazione di npoi e npoi.mapper (da Donnytian: https://github.com/donnytian/npoi.mapper) per importare facilmente i file Excel. Aggiungi un riferimento NUGET a NPOI e NPOI.Mapper e quindi è possibile importare dati XLS/XLSX utilizzando classi fortemente tipizzate correlate direttamente alle colonne che si desidera importare.
`` `Utilizzo di System.io; usando System.linq; usando npoi.mapper; usando npoi.mapper.attributes; usando npoi.ss.usermodel; utilizzando UserManagementservice.Models;
namespace jobcustomerimport.processors {classe pubblica ExcelEmailProcessor {private UserManagementserviceContext DataContext {get; }
public ExcelEmailProcessor(int customerNumber)
{
DataContext = new UserManagementServiceContext();
}
public void Execute(string localPath, int sheetIndex)
{
IWorkbook workbook;
using (FileStream file = new FileStream(localPath, FileMode.Open, FileAccess.Read))
{
workbook = WorkbookFactory.Create(file);
}
var importer = new Mapper(workbook);
var items = importer.Take<MurphyExcelFormat>(sheetIndex);
foreach(var item in items)
{
var row = item.Value;
if (string.IsNullOrEmpty(row.EmailAddress))
continue;
UpdateUser(row);
}
DataContext.SaveChanges();
}
private void UpdateUser(MurphyExcelFormat row)
{
//LOGIC HERE TO UPDATE A USER IN DATABASE...
}
private class MurphyExcelFormat
{
[Column("District")]
public int District { get; set; }
[Column("DM")]
public string FullName { get; set; }
[Column("Email Address")]
public string EmailAddress { get; set; }
[Column(3)]
public string Username { get; set; }
public string FirstName
{
get
{
return Username.Split('.')[0];
}
}
public string LastName
{
get
{
return Username.Split('.')[1];
}
}
}
}
} ```
Se sei interessato, ho coperto alcuni dei punti più fini del mio blog: Come importare facilmente i file Excel.
Grazie! Dan