Nella mia applicazione C# sto usando la stringa di connessione OLEDB "Provider=Microsoft.Jet.OLEDB.4.0;Data Source=c:\test.xls;Extended Properties=\"Excel 8.0;HDR=NO;ReadOnly=true;IMEX=1\"
" per leggere i file di Excel. Per leggere un file protetto da password ho provato ad aggiungere il campo password nella stringa di connessione ma non ho potuto leggere il file. Voglio sapere se esiste un modo per leggere i file Excel protetti da password usando OLEDB se conosco la sua password in anticipo.Leggere il file excel protetto tramite OLEDB in C#
risposta
Qui ci sono different ways to connect to an Excel file, incluso OLEDB. In base a ciò, non è possibile aprire un file protetto da password con metodi standard. Devi usare una soluzione alternativa.
Se la cartella di lavoro di Excel è protetto da una password , non è possibile aprirlo per l'accesso ai dati, anche fornendo il password corretta con la stringa di connessione . Se si tenta, è visualizzato il seguente messaggio di errore: "Impossibile il file decifrare
This is the solution, anche se non in C#, ma si potrebbe facilmente adattarlo per i vostri scopi
Se don'.. t conosce la password da soli, in alternativa è quello di ri-scrivere il file senza una password, è possibile utilizzare this handy project e aggiungere il seguente routine per esso:..
public void SaveFile()
{
this.excelWorkbook.SaveAs(
this.excelWorkbook.FullName,
vk_format,
"",
vk_write_res_password,
vk_read_only,
null,
Microsoft.Office.Interop.Excel.XlSaveAsAccessMode.xlNoChange,
null,
vk_add_to_mru,
null,null,vk_local);
}
È possibile utilizzare OoXmlCrypto stream per accedere ai file crittografati di Office 2007. Open source, include ExcelPackage modificato.
codice di esempio:
using (OfficeCryptoStream stream = OfficeCryptoStream.Open("a.xlsx", "password"))
{
// Do stuff (e.g. create System.IO.Packaging.Package or
// ExcelPackage from the stream, make changes and save)
// Change the password (optional)
stream.Password = "newPassword";
// Encrypt and save the file
stream.Save();
}
Se si utilizza una query per leggere il file di Excel, non importa se alcuni dei fogli sono protetti: funziona in entrambi i modi.
private string ExcelConnection(string fileName)
{
return
@"Provider=Microsoft.Jet.OLEDB.4.0;" +
@"Data Source=" + fileName + ";" +
@"Extended Properties=" + Convert.ToChar(34).ToString() +
@"Excel 8.0" + Convert.ToChar(34).ToString() + ";";
}
private DataTable readExcel(string fileName, string sql)
{
OleDbConnection conn = new OleDbConnection(ExcelConnection(fileName));
OleDbCommand cmd = new OleDbCommand(sql, conn);
OleDbDataAdapter adp = new OleDbDataAdapter();
adp.SelectCommand = cmd;
DataTable dt = new DataTable();
try
{
adp.FillSchema(dt, SchemaType.Source);
adp.Fill(dt);
}
catch
{
}
return dt;
}
Dopo aver ricercato ancora e ancora, finalmente ho trovato 2 cose.
1.Utilizzando OLEDB, non è possibile leggere il file excel protetto da password.
2.Anche se Interop può leggere il file excel, indipendentemente dal fatto che sia protetto da password o meno, le sue prestazioni non sono buone come quelle di OLEDB.
Così, ho creare sottostante Codice combinando
1. OLE DB, che ha prestazioni molto bello e
2. Interop che può leggere ogni file excel.
public DataTable ReadPasswordProtectedExcel(string ExcelFilePath, string Password)
{
String TempExcelFilePath = string.Empty;
DataTable _DataTable = new DataTable();
#region Get ExcelFile and Remove Password
{
String TempExcelFileName = string.Empty;
String DirectoryPath = string.Empty;
Microsoft.Office.Interop.Excel.Application excelapp = new Microsoft.Office.Interop.Excel.Application();
excelapp.Visible = false;
Microsoft.Office.Interop.Excel.Workbook newWorkbook = excelapp.Workbooks.Open(ExcelFilePath, 0,
true, 5, Password, "", false, Microsoft.Office.Interop.Excel.XlPlatform.xlWindows, "", true,
false, 0, true, false, false);
TempExcelFileName = string.Format("{0}_{1}", "__", Path.GetFileName(ExcelFilePath)); // __xxx.xlsx
TempExcelFilePath = String.Format("{0}/{1}", Path.GetDirectoryName(ExcelFilePath), TempExcelFileName);
/// Create new excel file and remove password.
newWorkbook.SaveAs(TempExcelFilePath, Microsoft.Office.Interop.Excel.XlFileFormat.xlWorkbookDefault, "", "",
false, false, Microsoft.Office.Interop.Excel.XlSaveAsAccessMode.xlNoChange,
Type.Missing, Type.Missing, Type.Missing, Type.Missing, Type.Missing);
newWorkbook.Close(true, "", false);
excelapp.Quit();
Marshal.ReleaseComObject(excelapp);
}
#endregion
#region Get data from excel file by using OLEDB
{
_DataTable = ReadExcelFileInOLEDB(TempExcelFilePath);
///Delete excel file
File.Delete(TempExcelFilePath);
}
#endregion
return _DataTable;
}
public DataTable ReadExcelFileInOLEDB(string _ExcelFilePath)
{
string ConnectionString = string.Empty;
string SheetName = string.Empty;
DataTable _DataTable = null;
DataSet _DataSet = null;
try
{
ConnectionString = string.Format("Provider=Microsoft.ACE.OLEDB.12.0;Data Source={0};Extended Properties='Excel 12.0;HDR=YES;IMEX=0;'", _ExcelFilePath);
using (OleDbConnection _OleDbConnection = new OleDbConnection(ConnectionString))
{
_OleDbConnection.Open();
_DataTable = _OleDbConnection.GetOleDbSchemaTable(OleDbSchemaGuid.Tables, null);
if (_DataTable == null)
return null;
SheetName = _DataTable.Rows[0]["TABLE_NAME"].ToString();
ConnectionString = string.Format("SELECT * FROM [{0}]", SheetName);
using (OleDbCommand _OleDbCommand = new OleDbCommand(ConnectionString, _OleDbConnection))
{
using (OleDbDataAdapter _OleDbDataAdapter = new OleDbDataAdapter())
{
_OleDbDataAdapter.SelectCommand = _OleDbCommand;
_DataSet = new DataSet();
_OleDbDataAdapter.Fill(_DataSet, "PrintInfo");
return _DataSet.Tables["PrintInfo"];
}
}
}
}
catch (Exception ex)
{
throw ex;
}
}
Infine, se si desidera rimuovere riga vuota durante il recupero di dati da Excel, si prega di controllare this link e sotto il codice
SELECT * FROM NAMED_RANGE WHERE [YourColumnTitle] IS NOT NULL
- 1. Prestazioni di OLEDB per leggere Excel
- 2. File Excel protetto da password
- 3. leggi .xlsx senza Excel e OLEDB
- 4. DBNullo nella cella non vuota durante la lettura del file Excel tramite OleDB
- 5. Come leggere il file Excel in Scala
- 6. Lettura da excel utilizzando il comando oledb
- 7. Quale è il migliore oggetto o database OLEDB o Excel
- 8. leggere il file excel utilizzando Apache POI
- 9. Come leggere il file di password protetto excel (.xls) con l'API POI
- 10. Aiuto con una stringa di connessione OleDB per file excel
- 11. I/O file non protetto in C/C++
- 12. Come leggere i dati da file Excel utilizzando C#
- 13. Impossibile aprire il file in Excel C#
- 14. Utilizzo di C# per leggere/scrivere file Excel (.xls/.xlsx)
- 15. Come convertire il file excel stream in C# datatable?
- 16. Perché ricevo un errore "oggetto Zip non valido o unitializzato" durante il tentativo di leggere il file excel tramite PHP?
- 17. Come leggere il file XML in C#?
- 18. Come leggere il file binario in C#?
- 19. OLEDB, Scrittura di una cella di Excel senza anticipo apostrofo
- 20. Leggere file json in C++
- 21. Come leggere una colonna CLOB in Oracle usando OleDb?
- 22. Come leggere il file excel omettendo le prime due righe
- 23. Impossibile salvare il file Excel utilizzando C#
- 24. Come leggere il codice di uscita di PowerShell tramite C#
- 25. Come leggere da XLSX (Excel)?
- 26. C# continua a leggere il file
- 27. come leggere i commenti del foglio Excel in C#
- 28. Come posso leggere i file Excel in Perl?
- 29. Come analizzare il file Excel in Javascript/HTML5
- 30. Come leggere un file Excel con JavaScript (senza ActiveXObject)
PWD = Password hai provato? – Havenard