如何在使用 C# 将 excel 转换为 Google 工作表时复制样式?
How to copy styling while converting excel to Google sheets using c#?
我有一个代码可以将 excel sheet 转换为 google sheet。
它正在工作,但仅复制值。
如何将样式和范围(合并的单元格)也复制到 google 表格?
是否还有一种更简单的方法来模拟我打开 google sheets 上的文件?
foreach (var sheet in wb.Worksheets)
{
if (sheet.Index == 0)
{
// First sheet is created by default, so only set range
range = $"{defaultWorksheetName}!A:Y";
}
else
{
// Add a new sheet
AddSheet(sheetService, spreadhsheet.SpreadsheetId, sheet.Name);
range = $"{sheet.Name}!A:Y";
}
// Get number of rows and columns
int rows = sheet.Cells.MaxDataRow;
int cols = sheet.Cells.MaxDataColumn;
IList<IList<Object>> list = new List<IList<Object>>() { };
// Loop through rows
for (int i = 0; i < rows; i++)
{
List<object> lists = new List<object>();
// Loop through each column in selected row
for (int j = 0; j < cols; j++)
{
lists.Add(sheet.Cells[i, j].Value);
}
list.Add(lists);
}
// Define range
ValueRange VRange = new ValueRange();
VRange.Range = range;
// Set values
VRange.Values = list;
// Create request
SpreadsheetsResource.ValuesResource.UpdateRequest upd = sheetService.Spreadsheets.Values.Update(VRange, spreadhsheet.SpreadsheetId, range);
upd.ValueInputOption = SpreadsheetsResource.ValuesResource.UpdateRequest.ValueInputOptionEnum.USERENTERED;
// Execute request
UpdateValuesResponse response = upd.Execute();
// Get response
string responseString = JsonConvert.SerializeObject(response);
}
您似乎正在遍历 Excel 行来创建一个对象来手动构建 Google Sheet。查看 Microsoft documentation,您可能还可以阅读这些单元格的格式并使用 Sheets API 来应用它,但是,这个过程似乎太过 time-consuming 和 error-prone.
我的建议是让 Google 为您完成这项工作。驱动器 API 能够 uploading Excel files and converting them to Google Sheets by setting the MimeType to application/vnd.google-apps.spreadsheet
. There are some limitations,但通常它能很好地保持单元格格式不变。
Google 的文档不包含 .NET 示例,我不是这方面的专家,但您可以查看他们的 .NET API which does have the Files.create
methods, or you could use their REST API。
来源:
我发现使用云端硬盘 API 而不是表格 API 并按原样上传文件,然后获取 link 会更好更容易在 Google 张中打开它。
public static string UploadFile(Stream file, string fileName, string fileMime, string fileDescription)
{
DriveService service = GetService();
var driveFile = new Google.Apis.Drive.v3.Data.File();
driveFile.Name = fileName;
driveFile.Description = fileDescription;
driveFile.MimeType = "application/vnd.google-apps.spreadsheet";
var request = service.Files.Create(driveFile, file, driveFile.MimeType);
request.Fields = "id, webViewLink";
var response = request.Upload();
if (response.Status != Google.Apis.Upload.UploadStatus.Completed)
throw response.Exception;
return request.ResponseBody.WebViewLink;
}
private static DriveService GetService()
{
string[] Scopes = { SheetsService.Scope.Drive };
string ApplicationName = "Excel to Google Sheet";
UserCredential credential = null;
using (var stream =
new FileStream("credentials.json", FileMode.Open, FileAccess.Read))
{
string credPath = "token.json";
var thread = new Thread(() =>
credential = GoogleWebAuthorizationBroker.AuthorizeAsync(
GoogleClientSecrets.FromStream(stream).Secrets,
Scopes,
"user",
CancellationToken.None,
new FileDataStore(credPath, true)).Result)
{ IsBackground = false };
thread.Start();
if (!thread.Join(20000))
{
throw new Exception("Timeout exception..!!!");
}
else
{
var service = new DriveService(new BaseClientService.Initializer()
{
HttpClientInitializer = credential,
ApplicationName = ApplicationName,
});
return service;
}
}
}
我有一个代码可以将 excel sheet 转换为 google sheet。 它正在工作,但仅复制值。
如何将样式和范围(合并的单元格)也复制到 google 表格?
是否还有一种更简单的方法来模拟我打开 google sheets 上的文件?
foreach (var sheet in wb.Worksheets)
{
if (sheet.Index == 0)
{
// First sheet is created by default, so only set range
range = $"{defaultWorksheetName}!A:Y";
}
else
{
// Add a new sheet
AddSheet(sheetService, spreadhsheet.SpreadsheetId, sheet.Name);
range = $"{sheet.Name}!A:Y";
}
// Get number of rows and columns
int rows = sheet.Cells.MaxDataRow;
int cols = sheet.Cells.MaxDataColumn;
IList<IList<Object>> list = new List<IList<Object>>() { };
// Loop through rows
for (int i = 0; i < rows; i++)
{
List<object> lists = new List<object>();
// Loop through each column in selected row
for (int j = 0; j < cols; j++)
{
lists.Add(sheet.Cells[i, j].Value);
}
list.Add(lists);
}
// Define range
ValueRange VRange = new ValueRange();
VRange.Range = range;
// Set values
VRange.Values = list;
// Create request
SpreadsheetsResource.ValuesResource.UpdateRequest upd = sheetService.Spreadsheets.Values.Update(VRange, spreadhsheet.SpreadsheetId, range);
upd.ValueInputOption = SpreadsheetsResource.ValuesResource.UpdateRequest.ValueInputOptionEnum.USERENTERED;
// Execute request
UpdateValuesResponse response = upd.Execute();
// Get response
string responseString = JsonConvert.SerializeObject(response);
}
您似乎正在遍历 Excel 行来创建一个对象来手动构建 Google Sheet。查看 Microsoft documentation,您可能还可以阅读这些单元格的格式并使用 Sheets API 来应用它,但是,这个过程似乎太过 time-consuming 和 error-prone.
我的建议是让 Google 为您完成这项工作。驱动器 API 能够 uploading Excel files and converting them to Google Sheets by setting the MimeType to application/vnd.google-apps.spreadsheet
. There are some limitations,但通常它能很好地保持单元格格式不变。
Google 的文档不包含 .NET 示例,我不是这方面的专家,但您可以查看他们的 .NET API which does have the Files.create
methods, or you could use their REST API。
来源:
我发现使用云端硬盘 API 而不是表格 API 并按原样上传文件,然后获取 link 会更好更容易在 Google 张中打开它。
public static string UploadFile(Stream file, string fileName, string fileMime, string fileDescription)
{
DriveService service = GetService();
var driveFile = new Google.Apis.Drive.v3.Data.File();
driveFile.Name = fileName;
driveFile.Description = fileDescription;
driveFile.MimeType = "application/vnd.google-apps.spreadsheet";
var request = service.Files.Create(driveFile, file, driveFile.MimeType);
request.Fields = "id, webViewLink";
var response = request.Upload();
if (response.Status != Google.Apis.Upload.UploadStatus.Completed)
throw response.Exception;
return request.ResponseBody.WebViewLink;
}
private static DriveService GetService()
{
string[] Scopes = { SheetsService.Scope.Drive };
string ApplicationName = "Excel to Google Sheet";
UserCredential credential = null;
using (var stream =
new FileStream("credentials.json", FileMode.Open, FileAccess.Read))
{
string credPath = "token.json";
var thread = new Thread(() =>
credential = GoogleWebAuthorizationBroker.AuthorizeAsync(
GoogleClientSecrets.FromStream(stream).Secrets,
Scopes,
"user",
CancellationToken.None,
new FileDataStore(credPath, true)).Result)
{ IsBackground = false };
thread.Start();
if (!thread.Join(20000))
{
throw new Exception("Timeout exception..!!!");
}
else
{
var service = new DriveService(new BaseClientService.Initializer()
{
HttpClientInitializer = credential,
ApplicationName = ApplicationName,
});
return service;
}
}
}