일부 Excel 파일이 공유 경로에서 SQL Server로 이동하지 않음
Excel 파일(공유 경로에 있음)의 데이터가 데이터베이스로 이동하는 응용 프로그램이 있습니다.오류가 발생한 경우 로그 파일에 오류를 기록하여 파일을 오류 폴더로 이동합니다.작업에 윈도우즈 서비스를 사용합니다.
파일에 오류가 없는 경우도 있지만 로그를 기록하여 오류 폴더로 이동합니다.External table is not in the expected format.그러나 동일한 파일을 한 번 또는 여러 번 다시 업로드하면 오류 없이 데이터베이스로 이동합니다.
Windows 서비스, DB 및 공유 경로가 XP Server에 있습니다.애플리케이션은 몇 년 동안 잘 실행되었습니다.그러나 최근에는 거의 모든 파일에서 위와 같은 문제가 발생하고 있습니다.
Microsoft 2003, 2007, 2012 사무실 구성 요소와 액세스 엔진도 설치했습니다.하지만 여전히 그 문제는 계속되고 있습니다.
나는 아래에 윈도우 서비스 코드를 언급하고 있습니다.제발 도와주세요.잘 부탁드립니다.
using System.IO;
using System;
using System.Collections.Generic;
using System.ComponentModel;
using System.Data;
using System.Diagnostics;
using System.Linq;
using System.ServiceProcess;
using System.Text;
using System.Data.SqlClient;
using System.Data.OleDb;
using System.Data.Common;
namespace Impexp_Service
{
public partial class Service1 : ServiceBase
{
System.Timers.Timer T1 = new System.Timers.Timer();
public Service1()
{
InitializeComponent();
}
protected override void OnStart(string[] args)
{
///start
///
{
SqlConnection strconnection = new SqlConnection();
strconnection.ConnectionString = @"Data Source=XXXXXX;Initial Catalog=XXXX;User ID=XX;Password=XXXXXX;";
strconnection.Open();
// To get the all files placed at the shared path
DirectoryInfo directory = new DirectoryInfo(@"D:\Impexp\Data\");
FileInfo[] files = directory.GetFiles("*.xlsx");
foreach (var f in files)
{
string path = f.FullName;
// TO establish connection to the excel sheet
string excelConnectionString = @"Provider=Microsoft.ACE.OLEDB.12.0;Data Source=" + path + ";Extended Properties=\"Excel 12.0;HDR=Yes;IMEX=1\";";
//Create Connection to Excel work book
OleDbConnection excelConnection = new OleDbConnection(excelConnectionString);
excelConnection.Open();
//Create OleDbCommand to fetch data from Excel
OleDbCommand cmd = new OleDbCommand("Select * from [Report$]", excelConnection);
DbDataReader dr = cmd.ExecuteReader();
// OleDbDataReader dReader;
// dReader = cmd.ExecuteReader();
SqlBulkCopy sqlBulk = new SqlBulkCopy(strconnection);
//Give your Destination table name
sqlBulk.DestinationTableName = "imp_master_test";
sqlBulk.WriteToServer(dr);
excelConnection.Close();
File.Delete(path);
// To move error files to the error folder
/// end
T1.Interval = 20000;
T1.Enabled = true;
T1.Start();
T1.Elapsed += new System.Timers.ElapsedEventHandler(T1_Elapsed);
}
}
}
void T1_Elapsed(object sender, System.Timers.ElapsedEventArgs e)
{
T1.Enabled = false;
try
{
SqlConnection strconnection = new SqlConnection();
strconnection.ConnectionString = @"Data Source=10.91.XXXXXX;Initial Catalog=XXXXX;User ID=XXXXX;Password=XXXXX;";
strconnection.Open();
// To get the all files placed at the shared path
DirectoryInfo directory = new DirectoryInfo(@"D:\Impexp\Data\");
FileInfo[] files = directory.GetFiles("*.xlsx");
foreach (var f in files)
{
string path = f.FullName;
// TO establish connection to the excel sheet
string excelConnectionString = @"Provider=Microsoft.ACE.OLEDB.12.0;Data Source=" + path + ";Extended Properties=\"Excel 12.0;HDR=Yes;IMEX=1\";";
//Create Connection to Excel work book
OleDbConnection excelConnection = new OleDbConnection(excelConnectionString);
try
{
excelConnection.Open();
//Create OleDbCommand to fetch data from Excel
OleDbCommand cmd = new OleDbCommand("Select * from [Report$]", excelConnection);
DbDataReader dr = cmd.ExecuteReader();
// OleDbDataReader dReader;
// dReader = cmd.ExecuteReader();
SqlBulkCopy sqlBulk = new SqlBulkCopy(strconnection);
//Give your Destination table name
sqlBulk.DestinationTableName = "imp_master_prod";
sqlBulk.WriteToServer(dr);
excelConnection.Close();
File.Delete(path);
}
// To move error files to the error folder
catch (Exception exp)
{
excelConnection.Close();
File.Move(path, Path.Combine(@"D:\Impexp\error\", f.Name));
string path1 = @"D:\Impexp\error\error.txt";
if (File.Exists(path1))
{
// Create a file to write to.
using (StreamWriter sw = File.AppendText(path1))
{
sw.WriteLine("File : " + path + " : " + exp.Message);
sw.Flush();
}
}
T1.Enabled = true;
T1.Start();
}
}
strconnection.Close();
// End of TRY 1
}
catch (UnauthorizedAccessException UAEx)
{
string path1 = @"D:\Impexp\error\error.txt";
if (File.Exists(path1))
{
// Create a file to write to.
using (StreamWriter sw = File.AppendText(path1))
{
sw.WriteLine(UAEx.Message);
sw.Flush();
}
}
T1.Enabled = true;
T1.Start();
}
catch (PathTooLongException PathEx)
{
string path1 = @"D:\Impexp\error\error.txt";
if (File.Exists(path1))
{
// Create a file to write to.
using (StreamWriter sw = File.AppendText(path1))
{
sw.WriteLine(PathEx.Message);
sw.Flush();
}
}
T1.Enabled = true;
T1.Start();
}
T1.Enabled = true;
T1.Start();
}
protected override void OnStop()
{
}
}
}
저는 OLEDB coms와 최신 버전의 엑셀에 대해 검색해 보았습니다.많은 사람들이 호환성 문제를 겪고 있는 것 같습니다.
불행하게도, 마이크로소프트는 이것에 관심을 기울이지 않는 것처럼 보입니다.Microsoft는 수년 전에 OLEDB 기능의 저하를 발표했으며, Office 제품 및 SQL 서버에 내부 지원을 추가하는 것을 중단했습니다.사실 MSAccess Web Apps and Web Databases의 공식 종료일은 2018년 4월이었습니다.따라서 서버, 클라이언트 버전의 윈도우 또는 클라이언트 버전의 Excel에 대한 업데이트가 이 문제를 유발했을 수 있으며 해결책은 없을 것으로 보입니다.저 자신도 해결책을 만들기 위해 머리를 벽에 부딪히는 것에 지쳤기 때문에 사무실 제품과의 연동을 처리하기 위해 타사 패키지(무료 패키지 사용 가능)를 사용하기 시작했습니다.솔직히, 접근 데이터베이스에 프로그래밍 방식으로 연결할 수 있는 기능을 제거하는 경우 접근 권한이 여전히 존재하는 이유를 알 수 없습니다.
이것이 여러분의 문제를 해결하지 못한다는 것을 알지만, 고쳐지지 않을 것을 고치려고 하는 것보다 진실을 직시하고 나아가는 것이 더 낫습니다.
이 질문을 보니 SQL 테이블이 아닌 엑셀 파일을 읽는 데 문제가 있는 것 같습니다.Excel 연결 문자열을 변경해 보십시오.
string excelConnectionString = @"Provider=Microsoft.ACE.OLEDB.12.0;Data Source=" + path + ";Extended Properties=\"Excel 12.0;HDR=Yes;IMEX=1\";";
로.
string excelConnectionString = @"Provider=Microsoft.ACE.OLEDB.12.0;Data Source=" + path + ";Extended Properties=Excel 12.0;HDR=Yes;IMEX=1\";
또한 다른 답변을 보면 근본 원인은 최신 버전의 엑셀을 업로드한 것일 수 있습니다.
다음을 사용하는 연결 문자열이 있는 Excel 2007 파일을 사용하고 있습니까?마이크로소프트.Jet.OLED B.4.0 및 확장 속성=Excel 8.0?
다음과 같이 문자열을 다른 문자열로 변경할 수 있습니다.
public static string path = @"C:\src\RedirectApplication\RedirectApplication\301s.xlsx";
public static string connStr = "Provider=Microsoft.ACE.OLEDB.12.0;Data Source=" + path + ";Extended Properties=Excel 12.0;";
OR
아래 링크에서 연결 문자열을 변경합니다. http://www.connectionstrings.com/excel-2007
언급URL : https://stackoverflow.com/questions/38120279/some-excel-files-not-moving-from-shared-path-to-sql-server
'programing' 카테고리의 다른 글
| SSIS 스크립트 구성 요소가 수동으로 열 때까지 어셈블리를 로드할 수 없음 (0) | 2023.07.11 |
|---|---|
| 외부 IP 주소에서 웹 서버에 액세스할 수 있도록 spring-boot을 설정하는 방법 (0) | 2023.07.11 |
| git reflog와 log의 차이점은 무엇입니까? (0) | 2023.07.11 |
| Oracle에 동등한 기능 포함 (0) | 2023.07.11 |
| Mongo 오류:토폴로지가 닫혔습니다. 데이터베이스 연결이 설정되었지만 연결하십시오. (0) | 2023.07.11 |